package com.emm.yixun.website.controller.customer;

//框架包
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.model.enums.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.anotations.UserOperateLog;
import com.emm.yixun.common.app.AddContactWayResDto;
import com.emm.yixun.common.app.AddCustomerReqDto;
import com.emm.yixun.common.app.AddCustomerResDto;
import com.emm.yixun.common.app.AddFollowReqDto;
import com.emm.yixun.common.app.AddFollowResDto;
import com.emm.yixun.common.app.DistributionConsultantReqDto;
import com.emm.yixun.common.app.DistributionConsultantResDto;
import com.emm.yixun.common.app.servletentity.ContentListReq;
import com.emm.yixun.common.app.servletentity.CustomerListReq;
import com.emm.yixun.common.app.servletentity.FamilyMemberListReq;
import com.emm.yixun.common.enums.FunctionTypeEnum;
import com.emm.yixun.common.enums.ModelTypeEnum;
import com.emm.yixun.common.model.Area;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.BusinessRelation;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.CustomerProjectQuestion;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.Image;
import com.emm.yixun.common.model.Merchant;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectHouseType;
import com.emm.yixun.common.model.ProjectPremises;
import com.emm.yixun.common.model.ProjectQuestionnaire;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.SalesGroup;
import com.emm.yixun.common.model.SalesGroupUser;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.AreaDto;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.BusinessRelationDto;
import com.emm.yixun.common.model.dto.ConvestObject;
import com.emm.yixun.common.model.dto.CustomerComponentDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.CustomerInfo;
import com.emm.yixun.common.model.dto.CustomerProjectQuestionDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.PayDepositDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectHouseTypeDto;
import com.emm.yixun.common.model.dto.ProjectPremisesDto;
import com.emm.yixun.common.model.dto.ProjectQuestionnaireDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.model.dto.SignedDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.EnumUtil;
import com.emm.yixun.customer.service.BusinessRelationServiceFacade;
import com.emm.yixun.customer.service.CustomerProjectQuestionServiceFacade;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.FamilyMemberServiceFacade;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.ProjectQuestionnaireServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.estate.service.ProjectHouseTypeServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.SalesGroupServiceFacade;
import com.emm.yixun.marketing.service.SalesGroupUserServiceFacade;
import com.emm.yixun.system.service.AreaServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.BusinessLogServiceFacade;
import com.emm.yixun.system.service.DictionaryServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.constant.ConstantConfig;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.task.utils.ArrayAssembly;
import com.emm.yixun.website.utils.ExcelUtil;
import com.emm.yixun.website.utils.SessionUtil;
import com.emm.yixun.website.vo.common.ExtResultVo;
//common
//common
//website
//变化的引用

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/customer/customer/")
public class CustomerController extends BaseController<Customer> {

	@Autowired
	private CustomerServiceFacade customerServiceFacade;

	@Autowired
	private DictionaryServiceFacade dictionaryServiceFacade;

	@Autowired
	private AreaServiceFacade areaServiceFacade;

	@Autowired
	private ProjectServiceFacade projectServiceFacade;

	@Autowired
	private UserServiceFacade userServiceFacade;

	@Autowired
	private FamilyMemberServiceFacade familyMemberServiceFacade;

	@Autowired
	private ProjectHouseTypeServiceFacade projectHouseTypeServiceFacade;

	@Autowired
	private ProjectPremisesServiceFacade projectPremisesServiceFacade;

	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;

	@Autowired
	private BusinessRelationServiceFacade businessRelationServiceFacade;

	@Autowired
	private SalesGroupServiceFacade salesGroupServiceFacade;

	@Autowired
	private SalesGroupUserServiceFacade salesGroupUserServiceFacade;

	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;

	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;

	@Autowired
	private SignedServiceFacade signedServiceFacade;

	@Autowired
	private MerchantServiceFacade merchantServiceFacade;

	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	
	@Autowired
	private ProjectQuestionnaireServiceFacade projectQuestionnaireServiceFacade;
	
	@Autowired
	private CustomerProjectQuestionServiceFacade customerProjectQuestionServiceFacade;

	@Autowired
	private ConstantConfig constantConfig;
	
	@Autowired
	private BusinessLogServiceFacade businessLogServiceFacade;

	@RequestMapping("index")
	@MerchantResourcesConfig(resourcesCode="menu_0006_0001")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response, ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:list")) {
			request.setAttribute("permitBtn", getPermissionBtnArray());
			request.setAttribute("resourcesCode", request.getParameter("menu"));
			// 数据权限
			User user = ShiroUtil.getCurrentUser();
			// 认筹开关,默认未关闭(false) ,true已关闭
			boolean payDepositOff = false;
			Response<Boolean> response2 = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response2.isSuccess()) {
				payDepositOff = response2.getEntity();
			}
			/*
			 * CustomerComponentDto dto = new CustomerComponentDto(); dto.setPermissionUserId(user.getId());
			 * dto.setMerchantId(user.getMerchantId()); dto.setResourcesCode(request.getParameter("menu"));
			 * dto.setOrders(" t.create_time desc "); List<Project> projects =
			 * customerServiceFacade.findProjectByDto(dto).getEntity(); com.alibaba.fastjson.JSONArray dtArray = new
			 * com.alibaba.fastjson.JSONArray(); if (projects != null && projects.size() != 0) { for (Project project :
			 * projects) { JSONObject row = new JSONObject(); row.put("id", project.getId()); row.put("projectName",
			 * project.getProjectName()); dtArray.add(row); } } map.put("projects", dtArray.toJSONString());
			 * map.put("projectId", projects != null && projects.size() != 0 ? projects.get(0).getId() : "kong");
			 */
			map.put("payDepositOff", payDepositOff);
			map.put("customerTemplet", constantConfig.getCustomerTemplet());
			//客户完善信息标志参数
			if(null != request.getParameter("improvenow")){
				map.put("improvenow",request.getParameter("improvenow"));
			}else{
				map.put("improvenow",0);
			}
			map.put("customerSort", user.getCustomerSort());
			map.put("customerHideField", user.getCustomerHideField());
			return new ModelAndView("/customer/customer/list");
		}
		return new ModelAndView(Const.NO_AUTHORIZED_URL);

	}

	@RequestMapping("indexLC")
	public ModelAndView indexLC(HttpServletRequest request, ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:list")) {
			request.setAttribute("permitBtn", getPermissionBtnArray());
			request.setAttribute("resourcesCode", request.getParameter("menu"));
			// 数据权限
			User user = ShiroUtil.getCurrentUser();
			// 认筹开关,默认未关闭(false) ,true已关闭
			boolean payDepositOff = false;
			Response<Boolean> response2 = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response2.isSuccess()) {
				payDepositOff = response2.getEntity();
			}
			/*
			 * CustomerComponentDto dto = new CustomerComponentDto(); dto.setPermissionUserId(user.getId());
			 * dto.setMerchantId(user.getMerchantId()); dto.setResourcesCode(request.getParameter("menu"));
			 * dto.setOrders(" t.create_time desc "); List<Project> projects =
			 * customerServiceFacade.findProjectByDto(dto).getEntity(); com.alibaba.fastjson.JSONArray dtArray = new
			 * com.alibaba.fastjson.JSONArray(); if (projects != null && projects.size() != 0) { for (Project project :
			 * projects) { JSONObject row = new JSONObject(); row.put("id", project.getId()); row.put("projectName",
			 * project.getProjectName()); dtArray.add(row); } } map.put("projects", dtArray.toJSONString());
			 * map.put("projectId", projects != null && projects.size() != 0 ? projects.get(0).getId() : "kong");
			 */
			map.put("payDepositOff", payDepositOff);
			map.put("customerTemplet", constantConfig.getCustomerTemplet());
			//客户完善信息标志参数
			if(null != request.getParameter("improvenow")){
				map.put("improvenow",request.getParameter("improvenow"));
			}else{
				map.put("improvenow",0);
			}
			map.put("customerSort", user.getCustomerSort());
			map.put("customerHideField", user.getCustomerHideField());
			map.put("serverDate", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
			return new ModelAndView("/customer/customer/listLC");
		}
		return new ModelAndView(Const.NO_AUTHORIZED_URL);

	}

	public static void main(String[] args) {
		StringBuffer cshySb = new StringBuffer();
		for (CongShiHangYeEnum cshy : CongShiHangYeEnum.values()) {
			cshySb.append(cshy.getDes());
			cshySb.append(",");
		}
		System.out.println(cshySb.toString());
		cshySb = new StringBuffer();
		for (CompanyXingZhiEnum cshy : CompanyXingZhiEnum.values()) {
			cshySb.append(cshy.getDes());
			cshySb.append(",");
		}
		System.out.println(cshySb.toString());
	}

	@RequestMapping("toAdd")
	@MerchantResourcesConfig(resourcesCode="menu_0006_0001_0001")
	public ModelAndView toAdd(HttpServletRequest request,HttpServletResponse response, String projectId, ModelMap map) {
		map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
		User user = ShiroUtil.getCurrentUser();
		String customerPhone = request.getParameter("customerPhone");
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		com.alibaba.fastjson.JSONArray dtArray = com.alibaba.fastjson.JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		String paymentMethod = convestJsonString(EnumUtil.toList(PaymentMethodEnum.class));
		// 学历
		String peAcademicQualifications = convestJsonString(EnumUtil.toList(PeAcademicQualificationsEnum.class));
		// 从事行业
		String congShiHangYeEnum = convestJsonString(EnumUtil.toList(CongShiHangYeEnum.class));
		// 公司性质
		String companyXingZhiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.CompanyXingZhiEnum.class));
		// 日常信息获取突进
		String riChangXinXiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.RiChangXinXiEnum.class));
		// 是否通用
		String isAvlidEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.IsAvlidEnum.class));
		// 家庭结构
		String familyJieEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.FamilyJieEnum.class));
		// 意向物业类型
		String yixiangwuyeType = convestJsonString(EnumUtil.toList(YiXiangWuYeEnum.class));
		// 需求户型规格
		String xuQiuHuXingEnum = convestJsonString(EnumUtil.toList(XuQiuHuXingEnum.class));
		// 买车意向
		String buyCarEnum = convestJsonString(EnumUtil.toList(BuyCarEnum.class));
		// 是否本公司业主
		String isOwnerCompanyEnum = convestJsonString(EnumUtil.toList(IsOwnerCompanyEnum.class));

		map.put("isOwnerCompanyEnum", isOwnerCompanyEnum);
		map.put("buyCarEnum", buyCarEnum);
		map.put("xuQiuHuXingEnum", xuQiuHuXingEnum);
		map.put("yixiangwuyeType", yixiangwuyeType);
		map.put("familyJieEnum", familyJieEnum);
		map.put("isAvlidEnum", isAvlidEnum);
		map.put("riChangXinXiEnum", riChangXinXiEnum);
		map.put("companyXingZhiEnum", companyXingZhiEnum);
		map.put("congShiHangYeEnum", congShiHangYeEnum);
		map.put("peAcademicQualifications", peAcademicQualifications);
		map.put("paymentMethod", paymentMethod);
		map.put("documentType", dtArray.toJSONString());
		map.put("resourcesCode", request.getParameter("menu"));
		map.put("userName", user.getUserName());
		map.put("projectId", projectId);
		map.put("customerPhone", customerPhone);
		return new ModelAndView("/customer/customer/add");
	}

	@RequestMapping("toAddLC")
	public ModelAndView toAddLC(HttpServletRequest request, String projectId, ModelMap map) {
		map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
		User user = ShiroUtil.getCurrentUser();
		String customerPhone = request.getParameter("customerPhone");
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		com.alibaba.fastjson.JSONArray dtArray = com.alibaba.fastjson.JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		String paymentMethod = convestJsonString(EnumUtil.toList(PaymentMethodEnum.class));
		// 学历
		String peAcademicQualifications = convestJsonString(EnumUtil.toList(PeAcademicQualificationsEnum.class));
		// 从事行业
		String congShiHangYeEnum = convestJsonString(EnumUtil.toList(CongShiHangYeEnum.class));
		// 公司性质
		String companyXingZhiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.CompanyXingZhiEnum.class));
		// 日常信息获取突进
		String riChangXinXiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.RiChangXinXiEnum.class));
		// 是否通用
		String isAvlidEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.IsAvlidEnum.class));
		// 家庭结构
		String familyJieEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.FamilyJieEnum.class));
		// 意向物业类型
		String yixiangwuyeType = convestJsonString(EnumUtil.toList(YiXiangWuYeEnum.class));
		// 需求户型规格
		String xuQiuHuXingEnum = convestJsonString(EnumUtil.toList(XuQiuHuXingEnum.class));
		// 买车意向
		String buyCarEnum = convestJsonString(EnumUtil.toList(BuyCarEnum.class));
		// 是否本公司业主
		String isOwnerCompanyEnum = convestJsonString(EnumUtil.toList(IsOwnerCompanyEnum.class));

		map.put("isOwnerCompanyEnum", isOwnerCompanyEnum);
		map.put("buyCarEnum", buyCarEnum);
		map.put("xuQiuHuXingEnum", xuQiuHuXingEnum);
		map.put("yixiangwuyeType", yixiangwuyeType);
		map.put("familyJieEnum", familyJieEnum);
		map.put("isAvlidEnum", isAvlidEnum);
		map.put("riChangXinXiEnum", riChangXinXiEnum);
		map.put("companyXingZhiEnum", companyXingZhiEnum);
		map.put("congShiHangYeEnum", congShiHangYeEnum);
		map.put("peAcademicQualifications", peAcademicQualifications);
		map.put("paymentMethod", paymentMethod);
		map.put("documentType", dtArray.toJSONString());
		map.put("resourcesCode", request.getParameter("menu"));
		map.put("userName", user.getUserName());
		map.put("projectId", projectId);
		map.put("customerPhone", customerPhone);
		map.put("serverDate", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));

		return new ModelAndView("/customer/customer/addLC");
	}


	public String convestJsonString(List<?> obj) {
		List<ConvestObject> jsonList = new ArrayList<ConvestObject>();
		for (int i = 0; i < obj.size(); i++) {
			ConvestObject os = new ConvestObject();
			BeanUtil.convert2T(os, obj.get(i));
			jsonList.add(os);
		}
		return JSONArray.fromObject(jsonList).toString();
	}

	@RequestMapping("toUpdate")
	@MerchantResourcesConfig(resourcesCode="menu_0006_0001_0002")
	public ModelAndView toUpdate(HttpServletRequest request, HttpServletResponse response,Long customerId, ModelMap map,  String returnUrl,String improve) {
		String paymentMethod = convestJsonString(EnumUtil.toList(PaymentMethodEnum.class));
		// 学历
		String peAcademicQualifications = convestJsonString(EnumUtil.toList(PeAcademicQualificationsEnum.class));
		// 从事行业
		String congShiHangYeEnum = convestJsonString(EnumUtil.toList(CongShiHangYeEnum.class));
		// 公司性质
		String companyXingZhiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.CompanyXingZhiEnum.class));
		// 日常信息获取突进
		String riChangXinXiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.RiChangXinXiEnum.class));
		// 是否通用
		String isAvlidEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.IsAvlidEnum.class));
		// 家庭结构
		String familyJieEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.FamilyJieEnum.class));

		// 意向物业类型
		String yixiangwuyeType = convestJsonString(EnumUtil.toList(YiXiangWuYeEnum.class));
		// 需求户型规格
		String xuQiuHuXingEnum = convestJsonString(EnumUtil.toList(XuQiuHuXingEnum.class));

		String buyCarEnum = convestJsonString(EnumUtil.toList(BuyCarEnum.class));
		// 是否本公司业主
		String isOwnerCompanyEnum = convestJsonString(EnumUtil.toList(IsOwnerCompanyEnum.class));
		map.put("isOwnerCompanyEnum", isOwnerCompanyEnum);
		map.put("buyCarEnum", buyCarEnum);
		map.put("xuQiuHuXingEnum", xuQiuHuXingEnum);
		map.put("yixiangwuyeType", yixiangwuyeType);
		map.put("familyJieEnum", familyJieEnum);
		map.put("isAvlidEnum", isAvlidEnum);
		map.put("riChangXinXiEnum", riChangXinXiEnum);
		map.put("companyXingZhiEnum", companyXingZhiEnum);
		map.put("congShiHangYeEnum", congShiHangYeEnum);
		map.put("peAcademicQualifications", peAcademicQualifications);
		map.put("paymentMethod", paymentMethod);
		map.put("resourcesCode", request.getParameter("menu"));
		if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
			map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "=").replace("*","&"));
		}
		if (!com.alibaba.druid.util.StringUtils.isEmpty(improve)) {
			map.put("improve",improve);
		}
		return new ModelAndView("/customer/customer/update").addObject("customerId", customerId);
	}

	@RequestMapping("toUpdateLC")
	public ModelAndView toUpdateLC(HttpServletRequest request, Long customerId, ModelMap map,  String returnUrl,String improve) {
		String paymentMethod = convestJsonString(EnumUtil.toList(PaymentMethodEnum.class));
		// 学历
		String peAcademicQualifications = convestJsonString(EnumUtil.toList(PeAcademicQualificationsEnum.class));
		// 从事行业
		String congShiHangYeEnum = convestJsonString(EnumUtil.toList(CongShiHangYeEnum.class));
		// 公司性质
		String companyXingZhiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.CompanyXingZhiEnum.class));
		// 日常信息获取突进
		String riChangXinXiEnum = convestJsonString(EnumUtil
				.toList(com.emm.yixun.common.model.enums.RiChangXinXiEnum.class));
		// 是否通用
		String isAvlidEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.IsAvlidEnum.class));
		// 家庭结构
		String familyJieEnum = convestJsonString(EnumUtil.toList(com.emm.yixun.common.model.enums.FamilyJieEnum.class));

		// 意向物业类型
		String yixiangwuyeType = convestJsonString(EnumUtil.toList(YiXiangWuYeEnum.class));
		// 需求户型规格
		String xuQiuHuXingEnum = convestJsonString(EnumUtil.toList(XuQiuHuXingEnum.class));

		String buyCarEnum = convestJsonString(EnumUtil.toList(BuyCarEnum.class));
		// 是否本公司业主
		String isOwnerCompanyEnum = convestJsonString(EnumUtil.toList(IsOwnerCompanyEnum.class));
		map.put("isOwnerCompanyEnum", isOwnerCompanyEnum);
		map.put("buyCarEnum", buyCarEnum);
		map.put("xuQiuHuXingEnum", xuQiuHuXingEnum);
		map.put("yixiangwuyeType", yixiangwuyeType);
		map.put("familyJieEnum", familyJieEnum);
		map.put("isAvlidEnum", isAvlidEnum);
		map.put("riChangXinXiEnum", riChangXinXiEnum);
		map.put("companyXingZhiEnum", companyXingZhiEnum);
		map.put("congShiHangYeEnum", congShiHangYeEnum);
		map.put("peAcademicQualifications", peAcademicQualifications);
		map.put("paymentMethod", paymentMethod);
		map.put("resourcesCode", request.getParameter("menu"));
		if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
			map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "=").replace("*","&"));
		}
		if (!com.alibaba.druid.util.StringUtils.isEmpty(improve)) {
			map.put("improve",improve);
		}
		return new ModelAndView("/customer/customer/updateLC").addObject("customerId", customerId);
	}


	@RequestMapping("toDetail")
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_1, modelName = ModelTypeEnum.MODELTYPE_0, projectKey = "projectId")
	@MerchantResourcesConfig(resourcesCode="menu_0006_0001_0004")
	public ModelAndView toDetail(Long customerId, String projectId, String resourcesCode, HttpServletRequest request,HttpServletResponse res) {
		User user = ShiroUtil.getCurrentUser();
		// 认筹开关,默认未关闭
		boolean payDepositOff = false;
		// 电话开关,默认关闭
		boolean callPhoneOff = true;
		try {
			request.setAttribute("permitBtn", getPermissionBtnArray());
			Response<Boolean> response = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response.isSuccess()) {
				payDepositOff = response.getEntity();
			}
			Response<Merchant> merchantResponse = merchantServiceFacade.findById(user.getMerchantId());
			if (merchantResponse.isSuccess() && null != merchantResponse) {
				Merchant merchant = merchantResponse.getEntity();
				String phoneInformation = merchant.getPhoneInformation();
				if (StringUtils.isNotEmpty(phoneInformation)) {
					com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(phoneInformation);
					if (null != jsonArray) {
						for (int ii = 0; ii < jsonArray.size(); ii++) {
							com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(ii);
							String type = jsonObject.getString("type");
							String status = jsonObject.getString("status");
							// type: 1代表电话开关, status: 1代表开启 0或为设置为关闭
							if ("1".equals(type) && "1".equals(status)) {
								// 认筹关闭
								callPhoneOff = false;
							}
						}
					}

				}
			}
			Response<Customer> customerRes = customerServiceFacade.findById(customerId);
			if(customerRes.isSuccess()){
				Customer customer = customerRes.getEntity();
				projectId = String.valueOf(customer.getProjectId());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView("/customer/customer/detail").addObject("customerId", customerId)
				.addObject("projectId", projectId).addObject("resourcesCode", resourcesCode)
				.addObject("payDepositOff", payDepositOff).addObject("callPhoneOff", callPhoneOff)
				.addObject("businessId", request.getParameter("businessId"));
	}
	
	@RequestMapping("toDetailLC")
	public ModelAndView toDetailLC(Long customerId, String projectId, String resourcesCode, HttpServletRequest request) {
		User user = ShiroUtil.getCurrentUser();
		// 认筹开关,默认未关闭
		boolean payDepositOff = false;
		// 电话开关,默认关闭
		boolean callPhoneOff = true;
		try {
			request.setAttribute("permitBtn", getPermissionBtnArray());
			Response<Boolean> response = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response.isSuccess()) {
				payDepositOff = response.getEntity();
			}
			Response<Merchant> merchantResponse = merchantServiceFacade.findById(user.getMerchantId());
			if (merchantResponse.isSuccess() && null != merchantResponse) {
				Merchant merchant = merchantResponse.getEntity();
				String phoneInformation = merchant.getPhoneInformation();
				if (StringUtils.isNotEmpty(phoneInformation)) {
					com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(phoneInformation);
					if (null != jsonArray) {
						for (int ii = 0; ii < jsonArray.size(); ii++) {
							com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(ii);
							String type = jsonObject.getString("type");
							String status = jsonObject.getString("status");
							// type: 1代表电话开关, status: 1代表开启 0或为设置为关闭
							if ("1".equals(type) && "1".equals(status)) {
								// 认筹关闭
								callPhoneOff = false;
							}
						}
					}
				}
			}
			Response<Customer> customerRes = customerServiceFacade.findById(customerId);
			if(customerRes.isSuccess()){
				Customer customer = customerRes.getEntity();
				projectId = String.valueOf(customer.getProjectId());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView("/customer/customer/detailLC").addObject("customerId", customerId)
				.addObject("projectId", projectId).addObject("resourcesCode", resourcesCode)
				.addObject("payDepositOff", payDepositOff).addObject("callPhoneOff", callPhoneOff)
				.addObject("businessId", request.getParameter("businessId")).addObject("giveUp", request.getParameter("giveUp"));
	}

	// @RequestMapping(value="index")
	// public String index(ModelMap map){
	// if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
	// //查询菜单按钮权限
	// map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
	// return "/customer/customer/list";
	// }
	// return Const.NO_AUTHORIZED_URL;
	// }

	/**
	 * 方法描述 : 获取房间信息 创建者：ThinkPad 项目名称： emm-website 类名： RoomMarketingController.java 版本： v1.0 创建时间： 2016年7月4日 下午1:45:58
	 * 
	 * @param customerId
	 * @return RoomInfo
	 */
	@RequestMapping(value = "findCustomerInfo")
	public @ResponseBody
	ExtResultVo findCustomerInfo(Long customerId) {
		ExtResultVo vo = new ExtResultVo();
		Response<CustomerInfo> response = customerServiceFacade.findInfoById(customerId);
		CustomerInfo customerInfo = response.getEntity();
		vo.setData(customerInfo);
		vo.setSuccess(true);
		return vo;
	}

	@RequestMapping(value = "findCustomerInfoCN")
	public @ResponseBody
	ExtResultVo findCustomerInfoCN(Long customerId) {
		ExtResultVo vo = new ExtResultVo();
		Response<CustomerInfo> response = customerServiceFacade.findInfoByIdCN(customerId);
		CustomerInfo customerInfo = response.getEntity();
		/*
		 * String rqFocusId=customerInfo.getRqFocusId(); if(StringUtils.isNotBlank(rqFocusId)){
		 * rqFocusId="["+rqFocusId+"]"; customerInfo.setRqFocusId(rqFocusId); }
		 */
		// 添加是否存在交易校驗
		boolean hasTrade = customerServiceFacade.checkCustomerLevel(customerId);
		customerInfo.setHasTrade(hasTrade);
		vo.setData(customerInfo);
		vo.setSuccess(true);
		return vo;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(CustomerDto dto, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		User user = ShiroUtil.getCurrentUser();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:add"))) {
			try {
				String[] rqFocusIds = request.getParameterValues("rqFocusId");
				String[] rqLifeSupports = request.getParameterValues("rqLifeSupport");// 生活配套
				String[] rqServicesIds = request.getParameterValues("rqServicesId");// 生活服务
				String[] peActivityTypes = request.getParameterValues("peActivityType");// 乐于参加的活动类型
				String[] richangxinxis = request.getParameterValues("richangxinxi");// 日常信息获取途径
				String[] peHobbyIds = request.getParameterValues("peHobbyId");// 兴趣爱好

				dto.setRqFocusId(getStr(rqFocusIds));
				dto.setRqLifeSupport(getStr(rqLifeSupports));
				dto.setRqServicesId(getStr(rqServicesIds));
				dto.setPeActivityType(getStr(peActivityTypes));
				dto.setRichangxinxi(getStr(richangxinxis));
				dto.setPeHobbyId(getStr(peHobbyIds));
				AddCustomerReqDto addCustomerReqDto = new AddCustomerReqDto();
				Response<Project> response = projectServiceFacade.findById(dto.getProjectId());
				Project project = response.getEntity();
				dto.setProjectCode(project.getProjectCode());
				dto.setUserCode(user.getUserCode());
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if (!dto.getFtContactTimes().equals("") && dto.getFtContactTimes() != null) {
					dto.setFtContactTime(sdf.parse(dto.getFtContactTimes()));
				}
				if (StringUtils.isNotBlank(request.getParameter("ftContactTimes1"))) {
					dto.setFtContactTime1(sdf.parse(request.getParameter("ftContactTimes1")));
				}
				BeanUtil.convert2T(addCustomerReqDto, dto);
				addCustomerReqDto = convestAddCustomerReqDto(addCustomerReqDto, dto);
				if (StringUtils.isNotBlank(dto.getGridJson())) {
					JSONArray jsonarray = JSONArray.fromObject(dto.getGridJson());
					@SuppressWarnings("unchecked")
					List<Object> objectList = (List<Object>) JSONArray.toCollection(jsonarray, Object.class);
					List<FamilyMemberListReq> view = new ArrayList<FamilyMemberListReq>();
					for (int i = 0; i < objectList.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList.get(i));
						FamilyMemberListReq sc = (FamilyMemberListReq) JSONObject.toBean(jsonObject,
								FamilyMemberListReq.class);
						sc.setProjectCode(dto.getProjectCode());
						sc.setMerchantId(user.getMerchantId() + "");
						view.add(sc);
					}
					addCustomerReqDto.setFamilyMemberList(view);
				}
				if (StringUtils.isNotBlank(dto.getGridJson2())) {
					JSONArray jsonarray2 = JSONArray.fromObject(dto.getGridJson2());
					@SuppressWarnings("unchecked")
					List<Object> objectList2 = (List<Object>) JSONArray.toCollection(jsonarray2, Object.class);
					List<String> view2 = new ArrayList<String>();
					for (int i = 0; i < objectList2.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList2.get(i));
						// String sc = (String)JSONObject.toBean(jsonObject,String.class);
						String sc = jsonObject.toString();
						// view2.add(sc);
						view2.add(sc);
					}
					addCustomerReqDto.setHouseTypeList(view2);
				}
				if (StringUtils.isNotBlank(dto.getGridJson3())) {
					JSONArray jsonarray3 = JSONArray.fromObject(dto.getGridJson3());
					@SuppressWarnings("unchecked")
					List<Object> objectList3 = (List<Object>) JSONArray.toCollection(jsonarray3, Object.class);
					List<String> view3 = new ArrayList<String>();
					for (int i = 0; i < objectList3.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList3.get(i));
						// String sc = (String)JSONObject.toBean(jsonObject,String.class);
						String sc = jsonObject.toString();
						view3.add(sc);
						// view3.add(dto.getGridJson3());
					}
					addCustomerReqDto.setPremisesList(view3);
				}
				if (StringUtils.isNotBlank(dto.getGridJson4())) {
					JSONArray jsonarray4 = JSONArray.fromObject(dto.getGridJson4());
					@SuppressWarnings("unchecked")
					List<Object> objectList4 = (List<Object>) JSONArray.toCollection(jsonarray4, Object.class);
					List<String> view4 = new ArrayList<String>();
					for (int i = 0; i < objectList4.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList4.get(i));
						// String sc = (String)JSONObject.toBean(jsonObject,String.class);
						String sc = jsonObject.toString();
						view4.add(sc);
						// view4.add(dto.getGridJson4());
					}
					addCustomerReqDto.setRoomList(view4);
				}
				if (StringUtils.isBlank(addCustomerReqDto.getRqDemandFloor())) {
					addCustomerReqDto.setRqDemandFloor(null);
				}
				if (StringUtils.isBlank(addCustomerReqDto.getRqLifeSupport())) {
					addCustomerReqDto.setRqLifeSupport(null);
				}
				if (StringUtils.isBlank(addCustomerReqDto.getReCurrentlyProperty())) {
					addCustomerReqDto.setReCurrentlyProperty(null);
				}
				CustomerDto customerDto = new CustomerDto();
				customerDto.setProjectId(addCustomerReqDto.getProjectId());
				customerDto.setCustomerPhone(addCustomerReqDto.getCustomerPhone()); //手机号码重复
				ResponseList<Customer> customerList = customerServiceFacade.findByDto(customerDto);
				if(customerList.isSuccess()&&customerList.getEntity()!=null&&customerList.getEntity().size()>0){
					if(customerList.getEntity().get(0).getGiveUpStatus().equals("0")){
						ar.setRes(99);
						return ar;
					}
				}
				
				//是否是已放弃的客户
				
				CustomerComponentDto component = new CustomerComponentDto();
				component.setProjectId(addCustomerReqDto.getProjectId());
				component.setCustomerPhone(addCustomerReqDto.getCustomerPhone());
				Page<CustomerComponentDto> customerCompnent = customerServiceFacade.findGiveUpPage(component,0, 10);
				if(customerCompnent.getRows()!=null&&customerCompnent.getRows().size()>0){
					ar.setRes(100);
					return ar;
				}
				
				AddCustomerResDto addCustomerResDto = customerServiceFacade.addCustomer(addCustomerReqDto, user);
				// Response<CustomerDto> response=customerServiceFacade.save(dto);
				if (addCustomerResDto.getResult().equals("1")) {
					ar.setSucceed(addCustomerResDto.getCustomerId());
					// ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				//新增业务操作异常记录
				businessLogServiceFacade.saveExceptionLog(user, "新增客户", com.alibaba.fastjson.JSONObject.toJSONString(dto), com.alibaba.fastjson.JSONObject.toJSONString(e));
				
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	public String getStr(String[] str) {
		if (null != str && str.length > 0) {
			StringBuffer strs = new StringBuffer("");
			for (String s : str) {
				if (StringUtils.isNotBlank(strs)) {
					strs.append(",");
				}
				strs.append(s);
			}
			return strs.toString();
		}
		return null;
	}

	/**
	 * 方法描述 : 属性转换,垃圾方式 创建者：ThinkPad 项目名称： emm-website 类名： CustomerController.java 版本： v1.0 创建时间： 2016年8月9日 下午6:54:55
	 * 
	 * @param dto
	 * @param entity
	 * @return AddCustomerReqDto
	 */
	public AddCustomerReqDto convestAddCustomerReqDto(AddCustomerReqDto dto, CustomerDto entity) {
		if (StringUtils.isNotBlank(entity.getRqPaymentMethod())) {
			PaymentMethodEnum paymentMethodEnum = PaymentMethodEnum.getByDescription(entity.getRqPaymentMethod());
			if (paymentMethodEnum != null) {
				dto.setRqPaymentMethod(paymentMethodEnum.getNo());
			}
		}
		dto.setFamilyStructure(entity.getFamilyJie());
		dto.setIndustry(entity.getCongshihangye());
		dto.setNatureCompany(entity.getCompanyXingzhi());
		dto.setAnnualTurnoverCompany(entity.getCompanyYingye());
		dto.setQqNum(entity.getQqNumber());
		dto.setIsEmployees(entity.getIsYuangong());
		dto.setIsOwnerCompany(entity.getIsYezhu());
		dto.setIsLiveElderly(entity.getIsLaoren());
		dto.setIsChildren(entity.getIsZinv());
		dto.setDailyInformation(entity.getRichangxinxi());
		dto.setIntentionPropertyType(entity.getYixiangwuyeType());
		dto.setSpecifications(entity.getXuqiuhuxingType());
		dto.setBuyParking(entity.getBuyCar());
		dto.setIsIntentionIntact(entity.getIsIntentionIntact());
		//20170728 st 用户状态更新
		dto.setCustomerStatus(entity.getCustomerStatus());

		return dto;
	}

	// 新增返回实体对象
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes update(CustomerDto dto, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		User user = ShiroUtil.getCurrentUser();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:edit"))) {
			try {
				String[] rqFocusIds = request.getParameterValues("rqFocusId");
				String[] rqLifeSupports = request.getParameterValues("rqLifeSupport");// 生活配套
				String[] rqServicesIds = request.getParameterValues("rqServicesId");// 生活服务
				String[] peActivityTypes = request.getParameterValues("peActivityType");// 乐于参加的活动类型
				String[] richangxinxis = request.getParameterValues("richangxinxi");// 日常信息获取途径
				String[] peHobbyIds = request.getParameterValues("peHobbyId");// 兴趣爱好

				dto.setRqFocusId(getStr(rqFocusIds));
				dto.setRqLifeSupport(getStr(rqLifeSupports));
				dto.setRqServicesId(getStr(rqServicesIds));
				dto.setPeActivityType(getStr(peActivityTypes));
				dto.setRichangxinxi(getStr(richangxinxis));
				dto.setPeHobbyId(getStr(peHobbyIds));
				AddCustomerReqDto addCustomerReqDto = new AddCustomerReqDto();
				Response<Project> response = projectServiceFacade.findById(dto.getProjectId());
				Project project = response.getEntity();
				dto.setProjectCode(project.getProjectCode());
				//编辑用户,不改变用户所属经纪人
				//dto.setUserCode(user.getUserCode());
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if (!dto.getFtContactTimes().equals("") && dto.getFtContactTimes() != null) {
					dto.setFtContactTime(sdf.parse(dto.getFtContactTimes()));
				}
				if (StringUtils.isNotBlank(request.getParameter("ftContactTimes1"))) {
					dto.setFtContactTime1(sdf.parse(request.getParameter("ftContactTimes1")));
				}
				BeanUtil.convert2T(addCustomerReqDto, dto);

				//JHSong: 存在交易,并且编辑信息后用户为非A级用户.提示错误
				boolean hasTrade = customerServiceFacade.checkCustomerLevel(addCustomerReqDto.getId());
				if(hasTrade && (!IntentionLevelEnum.A.getNo().equals(addCustomerReqDto.getIntentionLevel())
					&& !IntentionLevelEnum.A_PLUS.getNo().equals(addCustomerReqDto.getIntentionLevel()))){
					ar.setFailMsg("当前客户存在有效交易，不可进行降级操作！");
					return ar;
				}


				addCustomerReqDto = convestAddCustomerReqDto(addCustomerReqDto, dto);
				Response<Customer> customerResponse = customerServiceFacade.findById(dto.getId());
				Customer customer = customerResponse.getEntity();
				BusinessRelationDto entity = new BusinessRelationDto();
				entity.setProjectId(customer.getProjectId());
				entity.setSingleId(customer.getId());
				entity.setOrders(" t.create_time desc ");
				ResponseList<BusinessRelation> houseTypeResponse = customerServiceFacade.findBusinessByDto(entity);
				List<BusinessRelation> businessRelations = new ArrayList<BusinessRelation>();
				if (houseTypeResponse.getEntity() != null) {
					businessRelations = houseTypeResponse.getEntity();
					for (BusinessRelation businessRelation : businessRelations) {
						if (businessRelation.getRelationType().equals(RelationTypeEnum.HOUSE_TYPE.getNo())) {
							businessRelationServiceFacade.deleteByPrimaryKey(businessRelation.getId());
						}
						if (businessRelation.getRelationType().equals(RelationTypeEnum.PREMISES.getNo())) {
							businessRelationServiceFacade.deleteByPrimaryKey(businessRelation.getId());
						}
						if (businessRelation.getRelationType().equals(RelationTypeEnum.ROOM.getNo())) {
							businessRelationServiceFacade.deleteByPrimaryKey(businessRelation.getId());
						}
					}
				}
				FamilyMemberDto familyMemberDto = new FamilyMemberDto();
				familyMemberDto.setCustomerId(customer.getId());
				ResponseList<FamilyMember> familyMembersponse = familyMemberServiceFacade.findByDto(familyMemberDto);
				List<FamilyMember> familyMembers = new ArrayList<FamilyMember>();
				if (familyMembersponse.getEntity() != null) {
					familyMembers = familyMembersponse.getEntity();
					for (FamilyMember familyMember : familyMembers) {
						familyMemberServiceFacade.deleteByPrimaryKey(familyMember.getId());
					}
				}

				if (dto.getGridJson() != null || !dto.getGridJson().equals("")) {
					JSONArray jsonarray = JSONArray.fromObject(dto.getGridJson());
					@SuppressWarnings("unchecked")
					List<Object> objectList = (List<Object>) JSONArray.toCollection(jsonarray, Object.class);
					List<FamilyMemberListReq> view = new ArrayList<FamilyMemberListReq>();
					for (int i = 0; i < objectList.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList.get(i));
						FamilyMemberListReq sc = (FamilyMemberListReq) JSONObject.toBean(jsonObject,
								FamilyMemberListReq.class);
						sc.setProjectCode(dto.getProjectCode());
						sc.setMerchantId(user.getMerchantId() + "");
						if (StringUtils.isNotBlank(sc.getBirthday())) {
							if (sc.getBirthday().indexOf("T") != -1) {
								sc.setBirthday(sc.getBirthday().replace("T", " "));
							} else {
								sc.setBirthday(sdf.format(new Date(Long.valueOf(sc.getBirthday()))));
							}
						}
						if (StringUtils.isNotBlank(sc.getMarryday())) {
							if (sc.getMarryday().indexOf("T") != -1) {
								sc.setMarryday(sc.getMarryday().replace("T", " "));
							} else {
								sc.setMarryday(sdf.format(new Date(Long.valueOf(sc.getMarryday()))));
							}
						}
						view.add(sc);
					}
					addCustomerReqDto.setFamilyMemberList(view);
				}
				if (dto.getGridJson2() != null || !dto.getGridJson2().equals("")) {
					JSONArray jsonarray2 = JSONArray.fromObject(dto.getGridJson2());
					@SuppressWarnings("unchecked")
					List<Object> objectList2 = (List<Object>) JSONArray.toCollection(jsonarray2, Object.class);
					List<String> view2 = new ArrayList<String>();
					for (int i = 0; i < objectList2.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList2.get(i));
						// String sc = (String)JSONObject.toBean(jsonObject,String.class);
						String sc = jsonObject.toString();
						// view2.add(sc);
						view2.add(sc);
					}
					addCustomerReqDto.setHouseTypeList(view2);
				}
				if (dto.getGridJson3() != null || !dto.getGridJson3().equals("")) {
					JSONArray jsonarray3 = JSONArray.fromObject(dto.getGridJson3());
					@SuppressWarnings("unchecked")
					List<Object> objectList3 = (List<Object>) JSONArray.toCollection(jsonarray3, Object.class);
					List<String> view3 = new ArrayList<String>();
					for (int i = 0; i < objectList3.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList3.get(i));
						// String sc = (String)JSONObject.toBean(jsonObject,String.class);
						String sc = jsonObject.toString();
						view3.add(sc);
						// view3.add(dto.getGridJson3());
					}
					addCustomerReqDto.setPremisesList(view3);
				}
				addCustomerReqDto.setId(dto.getId());
				if (dto.getGridJson4() != null || !dto.getGridJson4().equals("")) {
					dto.getGridJson4().replaceAll("\\\\", "");
					JSONArray jsonarray4 = JSONArray.fromObject(dto.getGridJson4());
					@SuppressWarnings("unchecked")
					List<Object> objectList4 = (List<Object>) JSONArray.toCollection(jsonarray4, Object.class);
					List<String> view4 = new ArrayList<String>();
					for (int i = 0; i < objectList4.size(); i++) {
						JSONObject jsonObject = JSONObject.fromObject(objectList4.get(i));
						// String sc = (String)JSONObject.toBean(jsonObject,String.class);
						String sc = jsonObject.toString();
						view4.add(sc);
						// view4.add(dto.getGridJson4());
					}
					addCustomerReqDto.setRoomList(view4);
				}
				//2017.7.31 st 更新用户添加更新时间（用于检查用户最新被编辑的时间【不包含状态这类的更新】）
				if("1".equals(customer.getIsIntentionIntact()) && !"1".equals(dto.getIsIntentionIntact())) {
					addCustomerReqDto.setFillInfoTime(new Date());
				}

				AddCustomerResDto addCustomerResDto = customerServiceFacade.updateCustomer(addCustomerReqDto, user);
				// Response<CustomerDto> response=customerServiceFacade.save(dto);
				if (addCustomerResDto.getResult().equals("1")) {
					ar.setSucceed(addCustomerReqDto.getId());
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				//新增业务操作异常记录
				businessLogServiceFacade.saveExceptionLog(user, "修改客户", com.alibaba.fastjson.JSONObject.toJSONString(dto), com.alibaba.fastjson.JSONObject.toJSONString(e));
				
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 写跟进
	@RequestMapping(value = "addFollow")
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_6, modelName = ModelTypeEnum.MODELTYPE_0, projectKey = "projectId")
	public AjaxRes addFollow(AddFollowReqDto dto, String customerId, String followContents, String nextFollowH) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:addFollow"))) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				ContentListReq contentListReq = new ContentListReq();
				contentListReq.setFollowContent(followContents);
				if (dto.getNextFollowQ() != null && !dto.getNextFollowQ().equals("") && nextFollowH != null
						&& !nextFollowH.equals("")) {
					String getSignInfo = dto.getNextFollowQ().substring(dto.getNextFollowQ().indexOf(",") + 1);
					String getSignInfo2 = nextFollowH.substring(nextFollowH.indexOf(",") + 1);
					dto.setNextFollowTime(sdf.parse(getSignInfo + " " + getSignInfo2 + ":00"));
				}
				List<ContentListReq> contentListReqs = new ArrayList<ContentListReq>();
				contentListReqs.add(contentListReq);
				User user = ShiroUtil.getCurrentUser();
				dto.setUserId(user.getId() + "");
				Response<Project> response = projectServiceFacade.findById(dto.getProjectId());
				Project project = response.getEntity();
				dto.setProjectCode(project.getProjectCode());
				dto.setUserCode(user.getUserCode());
				dto.setMerchantId(user.getMerchantId());
				dto.setFollowType("1");
				// 如果跟进ID不为空，则说明是拨打电话跟进
				if (null != dto.getFollowId() && dto.getFollowId() > 0) {
				} else {
					dto.setFollowId(null);
				}

				dto.setContentList(contentListReqs);
				AddFollowResDto addFollowResDto = customerServiceFacade.addFollow(dto);

				if (addFollowResDto.getResult().equals("1")) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 分配
	@RequestMapping(value = "distributionConsultant")
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_10, modelName = ModelTypeEnum.MODELTYPE_0, projectKey = "projectId")
	public AjaxRes distributionConsultant(DistributionConsultantReqDto dto, String customerId) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:distributionConsultant"))) {
			try {
				String errorMsg = "存在对应业务,无法操作";
				User user = ShiroUtil.getCurrentUser();
				// if (customerId.indexOf(",") != -1) {
				String[] customerIds = customerId.split(",");
				int successCount = 0;
				Response<SalesGroup> sResponse = salesGroupServiceFacade.findById(dto.getProjectId());
				SalesGroup salesGroup = sResponse.getEntity();
				for (String id : customerIds) {
					if (id != null && id != "") {
						dto.setUserId(user.getId() + "");
						//此处的项目为分配后的项目
						Response<Project> response = projectServiceFacade.findById(salesGroup.getProjectId());
						Project project = response.getEntity();
						dto.setProjectId(project.getId());
						dto.setProjectCode(project.getProjectCode());
						dto.setUserCode(user.getUserCode());
						dto.setMerchantId(user.getMerchantId());

						//组装用户Id,需要List参数
						CustomerListReq customerListReq = new CustomerListReq();
						customerListReq.setCustomerId(id);
						List<CustomerListReq> customerListReqs = new ArrayList<CustomerListReq>();
						customerListReqs.add(customerListReq);
						dto.setCustomerList(customerListReqs);
						DistributionConsultantResDto distributionConsultantResDto = customerServiceFacade.distributionConsultant(dto);
						if (distributionConsultantResDto.getResult().equals("1")) {
							successCount++;
						} else {
							errorMsg = distributionConsultantResDto.getErrorMsg();
						}
					}
				}
				if (successCount == customerIds.length) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(errorMsg);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:view"))) {
			try {
				Response<Customer> response = customerServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(CustomerDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:edit"))) {
			try {
				Response<Integer> response = customerServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:delete"))) {
			try {
				boolean status = true;
				PayDepositDto payDepositDto = new PayDepositDto();
				payDepositDto.setCustomerId(id);
				ResponseList<PayDeposit> payDeposits = payDepositServiceFacade.findByDto(payDepositDto);
				if (payDeposits.isSuccess()) {
					if (payDeposits.getEntity() != null && payDeposits.getEntity().size() != 0) {
						ar.setFailMsg("此客户存在认筹记录，不允许删除！");
						return ar;
					}
				}
				SubscribeDto subscribeDto = new SubscribeDto();
				subscribeDto.setCustomerId(id);
				ResponseList<Subscribe> subscribes = subscribeServiceFacade.findByDto(subscribeDto);
				if (subscribes.isSuccess()) {
					if (subscribes.getEntity() != null && subscribes.getEntity().size() != 0) {
						ar.setFailMsg("此客户存在认购记录，不允许删除！");
						return ar;
					}
				}
				SignedDto signedDto = new SignedDto();
				signedDto.setCustomerId(id);
				ResponseList<Signed> signeds = signedServiceFacade.findByDto(signedDto);
				if (signeds.isSuccess()) {
					if (signeds.getEntity() != null && signeds.getEntity().size() != 0) {
						ar.setFailMsg("此客户存在签约记录，不允许删除！");
						return ar;
					}
				}
				if (status) {
					Response<Integer> response = customerServiceFacade.deleteByPrimaryKey(id);
					if (response.isSuccess()) {
						ar.setSucceedMsg(Const.DEL_SUCCEED);
					} else {
						ar.setFailMsg(Const.DEL_FAIL);
					}
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes list(CustomerDto dto, Integer pageSize, Integer pageNum) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:list"))) {
			try {
				Page<Customer> response = customerServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),
						pageSize);
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<Customer>());
					response.setPageNumber(pageNum);
					ar.setSucceed(response);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "customerComponentList", method = RequestMethod.POST)
	@ResponseBody
	public Page<CustomerComponentDto> customerComponentList(CustomerComponentDto dto, Integer page, Integer limit,
			String resourcesCode) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			User user = ShiroUtil.getCurrentUser();
			if (StringUtils.isNoneBlank(resourcesCode)) {
				dto.setResourcesCode(resourcesCode);
				dto.setPermissionUserId(user.getId());
				
			}
			dto.setMerchantId(user.getMerchantId());
			Page<CustomerComponentDto> response = customerServiceFacade.findCustomerComponentPage(dto,
					PageUtil.begin(page, limit), limit);
			if (response.getSuccess()) {
				if (null == response.getRows())
					response.setRows(new ArrayList<CustomerComponentDto>());
				response.setPageNumber(page);
			}
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<CustomerComponentDto>();
	}

	// 分页查询
	@RequestMapping(value = "customerList")
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_0, modelName = ModelTypeEnum.MODELTYPE_0, projectKey = "projectId")
	public Page<CustomerComponentDto> customerList(CustomerComponentDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			dto = setCustValue(dto);
			//当列表为未完善客户信息时只显示A级客户
			if(dto.getFillInfoDay() == 1){
				dto.setIntentionLevel("2");
			}
			User user = ShiroUtil.getCurrentUser();
			if(StringUtils.isNotBlank(user.getCustomerSort())) {
				String[] sort = user.getCustomerSort().split(" ");
				dto.setOrders(isUpperCase(sort[0]) + " " + sort[1]);
			} else {
				dto.setOrders("t.last_follow_time desc");
			}
			//当项目选择为全部时，只查询用户所有可以查看的项目
			if(dto.getProjectId() == null) {
				dto.setProjectIds(projectIds(user.getId(), user.getMerchantId()));
			}
			Page<CustomerComponentDto> response = customerServiceFacade.findCustomerPage(dto,
					PageUtil.begin(page, limit), limit);
			if (response.getSuccess()) {
				if (null == response.getRows())
					response.setRows(new ArrayList<CustomerComponentDto>());
				response.setPageNumber(page);
			}
			response.setError(response.getErrorMsg());
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<CustomerComponentDto>();
	}
	
	/**  
     * 根据char的工具类Character判断大写字母并格式化
     */ 
	private String isUpperCase(String str) {
		StringBuffer sb = new StringBuffer();
        char[] chars = str.toCharArray();  
        for (int i = 0, length = chars.length; i < length; i++) {  
            char c = chars[i];  
            //判断字母是不是大写，在字母前拼接"_"
            if (Character.isUpperCase(c)){  
            	sb.append("_");
            }  
            sb.append(c); 
        }  
        return sb.toString();
	}

	// 分页查询
	@RequestMapping(value = "customerListIntention")
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_0, modelName = ModelTypeEnum.MODELTYPE_0, projectKey = "projectId")
	public Page<CustomerComponentDto> customerListIntention(CustomerComponentDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			dto = setCustValue(dto);
			Page<CustomerComponentDto> response = customerServiceFacade.findCustomerIntentionPage(dto,
					PageUtil.begin(page, limit), limit);
			if (response.getSuccess()) {
				if (null == response.getRows())
					response.setRows(new ArrayList<CustomerComponentDto>());
				response.setPageNumber(page);
			}
			response.setError(response.getErrorMsg());
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<CustomerComponentDto>();
	}


	public CustomerComponentDto setCustValue(CustomerComponentDto dto) {
		if (dto.getFtContactTimeAfter() != null && !dto.getFtContactTimeAfter().equals("")) {
			dto.setFtContactTimeAfter(dto.getFtContactTimeAfter() + " 23:59:59");
		}
		//最新跟进时间
		if (StringUtils.isNotBlank(dto.getLastFollowTimeBefore())) {
			dto.setLastFollowTimeBefore(dto.getLastFollowTimeBefore() + " 00:00:00");
		}
		if (StringUtils.isNotBlank(dto.getLastFollowTimeAfter())) {
			dto.setLastFollowTimeAfter(dto.getLastFollowTimeAfter() + " 23:59:59");
		}
		//录入时间（即为业务创建时间）
		if (StringUtils.isNotBlank(dto.getCreateTimeBefore())) {
			dto.setCreateTimeBefore(dto.getCreateTimeBefore() + " 00:00:00");
		}

		if (StringUtils.isNotBlank(dto.getCreateTimeAfter())) {
			dto.setCreateTimeAfter(dto.getCreateTimeAfter() + " 23:59:59");
		}
		if (dto.getUserCode() != null && dto.getUserCode().equals("-1")) {
			dto.setUserCode(null);
		}

		// 数据权限
		User user = ShiroUtil.getCurrentUser();
		dto.setPermissionUserId(user.getId());
		dto.setMerchantId(user.getMerchantId());
		dto.setOrders(" t.create_time desc ");
		dto.setGiveUpStatus("0");
		return dto;
	}
	/**
	 * 获取当前用户可以查看的所有项目
	 * @param userId
	 * @param merchantId
	 * @return
	 */
	private String projectIds(Long userId, Long merchantId) {
		ProjectDto dto = new ProjectDto();
		dto.setResourcesCode("menu_0003_0001");
		dto.setResourcesName("resName_pro_list");
		// 项目数据权限资源缓存
		String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
		if (null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())) {
			dto.setResourcesCode(resourcesCode);
		} else if ("".equals(resourcesCode)) {
			ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
		}
		dto.setDelFlag("0");
		dto.setPermissionUserId(userId);
		dto.setMerchantId(merchantId);
		ResponseList<Project> projectList = projectServiceFacade.findByDto(dto);
		if(!projectList.isSuccess() || projectList.getEntity() == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < projectList.getEntity().size(); i++) {
			Project pro = (Project)projectList.getEntity().get(i);
			sb.append(pro.getId());
			if(i < projectList.getEntity().size()-1) {
				sb.append(",");
			}
		}
		return sb.toString();
	}

	@RequestMapping("selectCusType")
	public @ResponseBody
	Integer selectCusType(CustomerComponentDto dto, String tab) {
		dto = setCustValue(dto);
		dto.setTabType(tab);
		return customerServiceFacade.selectCustomerCount(dto).getEntity();
	}

	// 分页查询
	@RequestMapping(value = "userList")
	@ResponseBody
	public Page<User> userList(UserDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			// 数据权限
			User user = ShiroUtil.getCurrentUser();
			dto.setPermissionUserId(user.getId());
			dto.setMerchantId(user.getMerchantId());
			dto.setOrders(" t.create_time desc ");
			Page<User> response = userServiceFacade.findPageByDto(dto, PageUtil.begin(page, limit), limit);
			if (response.getSuccess()) {
				if (null == response.getRows())
					response.setRows(new ArrayList<User>());
				response.setPageNumber(page);
			}
			response.setError(response.getErrorMsg());
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<User>();
	}

	// 分页查询
	@RequestMapping(value = "familyMemberList")
	@ResponseBody
	public Page<FamilyMember> familyMemberList(FamilyMemberDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			dto.setOrders(" t.create_time desc ");
			dto.setMemberType("1");// 家庭成员
			Page<FamilyMember> response = familyMemberServiceFacade.findPageByDto(dto, PageUtil.begin(page, limit),
					limit);
			if (response.getSuccess()) {
				if (null == response.getRows())
					response.setRows(new ArrayList<FamilyMember>());
				response.setPageNumber(page);
			}
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<FamilyMember>();
	}

	// 分页查询
	@RequestMapping(value = "imageList")
	@ResponseBody
	public Page<Image> imageList(ImageDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			User user = ShiroUtil.getCurrentUser();
			dto.setMerchantId(user.getMerchantId());
			dto.setOrders(" t.create_time desc ");
			Page<Image> response = customerServiceFacade.findImagePageByDto(dto, PageUtil.begin(page, limit), limit);
			if (response.getSuccess()) {
				if (null == response.getRows())
					response.setRows(new ArrayList<Image>());
				response.setPageNumber(page);
			}
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<Image>();
	}

	// 查询所有
	@RequestMapping(value = "getImageList", method = RequestMethod.POST)
	@ResponseBody
	public List<Image> getImageList(ImageDto dto) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		List<Image> list = new ArrayList<Image>();
		try {
			User user = ShiroUtil.getCurrentUser();
			dto.setMerchantId(user.getMerchantId());
			dto.setOrders(" t.create_time desc ");
			ResponseList<Image> response = customerServiceFacade.selectListByDto(dto);
			if (response.isSuccess()) {
				list = response.getEntity();
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return list;
	}

	// 分页查询
	@RequestMapping(value = "houseTypeList")
	@ResponseBody
	public Page<ProjectHouseTypeDto> houseTypeList(BusinessRelationDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			Response<Customer> customerResponse = customerServiceFacade.findById(dto.getCustomerId());
			Customer customer = customerResponse.getEntity();
			dto.setProjectId(customer.getProjectId());
			dto.setSingleId(customer.getId());
			dto.setOrders(" t.create_time desc ");
			ResponseList<BusinessRelation> houseTypeResponse = customerServiceFacade.findBusinessByDto(dto);
			List<BusinessRelation> businessRelations = new ArrayList<BusinessRelation>();
			List<ProjectHouseTypeDto> projectHouseTypes = new ArrayList<ProjectHouseTypeDto>();
			if (houseTypeResponse.getEntity() != null) {
				businessRelations = houseTypeResponse.getEntity();
				for (BusinessRelation businessRelation : businessRelations) {
					if (businessRelation.getRelationType().equals(RelationTypeEnum.HOUSE_TYPE.getNo())) {
						ProjectHouseTypeDto projectHouseTypeDto = new ProjectHouseTypeDto();
						projectHouseTypeDto.setId(businessRelation.getMoreId());
						Response<ProjectHouseType> houseType = projectHouseTypeServiceFacade.findById(businessRelation
								.getMoreId());
						BeanUtils.copyProperties(houseType.getEntity(), projectHouseTypeDto);
						projectHouseTypeDto.setHouseTypeId(projectHouseTypeDto.getId());
						projectHouseTypes.add(projectHouseTypeDto);
					}
				}
			}
			Page<ProjectHouseTypeDto> response = new Page<ProjectHouseTypeDto>(projectHouseTypes.size(),
					projectHouseTypes);
			response.setPageSize(limit);
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<ProjectHouseTypeDto>();
	}

	// 分页查询
	@RequestMapping(value = "premisesList")
	@ResponseBody
	public Page<ProjectPremisesDto> premisesList(BusinessRelationDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			Response<Customer> customerResponse = customerServiceFacade.findById(dto.getCustomerId());
			Customer customer = customerResponse.getEntity();
			dto.setProjectId(customer.getProjectId());
			dto.setSingleId(customer.getId());
			dto.setOrders(" t.create_time desc ");
			ResponseList<BusinessRelation> houseTypeResponse = customerServiceFacade.findBusinessByDto(dto);
			List<BusinessRelation> businessRelations = new ArrayList<BusinessRelation>();
			List<ProjectPremisesDto> projectPremises = new ArrayList<ProjectPremisesDto>();
			if (houseTypeResponse.getEntity() != null) {
				businessRelations = houseTypeResponse.getEntity();
				for (BusinessRelation businessRelation : businessRelations) {
					if (businessRelation.getRelationType().equals(RelationTypeEnum.PREMISES.getNo())) {
						ProjectPremisesDto projectPremisesDto = new ProjectPremisesDto();
						projectPremisesDto.setId(businessRelation.getMoreId());
						Response<ProjectPremises> projectPremise = projectPremisesServiceFacade
								.findById(businessRelation.getMoreId());
						BeanUtils.copyProperties(projectPremise.getEntity(), projectPremisesDto);
						projectPremisesDto.setPremisesId(projectPremisesDto.getId());
						projectPremises.add(projectPremisesDto);
					}
				}
			}
			Page<ProjectPremisesDto> response = new Page<ProjectPremisesDto>(projectPremises.size(), projectPremises);
			response.setPageSize(limit);
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<ProjectPremisesDto>();
	}

	// 分页查询
	@RequestMapping(value = "roomList")
	@ResponseBody
	public Page<ProjectRoomDto> roomList(BusinessRelationDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			Response<Customer> customerResponse = customerServiceFacade.findById(dto.getCustomerId());
			Customer customer = customerResponse.getEntity();
			dto.setProjectId(customer.getProjectId());
			dto.setSingleId(customer.getId());
			dto.setOrders(" t.create_time desc ");
			ResponseList<BusinessRelation> houseTypeResponse = customerServiceFacade.findBusinessByDto(dto);
			List<BusinessRelation> businessRelations = new ArrayList<BusinessRelation>();
			List<ProjectRoomDto> projectRooms = new ArrayList<ProjectRoomDto>();
			if (houseTypeResponse.getEntity() != null) {
				businessRelations = houseTypeResponse.getEntity();
				for (BusinessRelation businessRelation : businessRelations) {
					if (businessRelation.getRelationType().equals(RelationTypeEnum.ROOM.getNo())) {
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						projectRoomDto.setId(businessRelation.getMoreId());
						Response<ProjectRoom> projectRoom = projectRoomServiceFacade.findById(businessRelation
								.getMoreId());
						BeanUtils.copyProperties(projectRoom.getEntity(), projectRoomDto);
						projectRoomDto.setRoomId(projectRoomDto.getId());
						projectRooms.add(projectRoomDto);
					}
				}
			}
			Page<ProjectRoomDto> response = new Page<ProjectRoomDto>(projectRooms.size(), projectRooms);
			response.setPageSize(limit);
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<ProjectRoomDto>();
	}

	@RequestMapping(value = "returnDictionaryList")
	@ResponseBody
	public List<Dictionary> returnDictionaryList(String typeName) {
		DictionaryDto dictionaryDto = new DictionaryDto();
		dictionaryDto.setDictionaryType(typeName);
		ResponseList<Dictionary> dResponseList = dictionaryServiceFacade.findByDto(dictionaryDto);
		List<Dictionary> dictionaryList = new ArrayList<Dictionary>();
		if (dResponseList != null) {
			dictionaryList = dResponseList.getEntity();
		}
		return dictionaryList;
	}

	// 关注户型
	@RequestMapping(value = "projectHouseTypeList")
	@ResponseBody
	public List<ProjectHouseType> projectHouseTypeList(Long projectId) {
		ProjectHouseTypeDto projectHouseTypeDto = new ProjectHouseTypeDto();
		projectHouseTypeDto.setProjectId(projectId);
		ResponseList<ProjectHouseType> dResponseList = projectHouseTypeServiceFacade.findByDto(projectHouseTypeDto);
		List<ProjectHouseType> projectHouseTypes = new ArrayList<ProjectHouseType>();
		if (dResponseList != null) {
			projectHouseTypes = dResponseList.getEntity();
		}
		return projectHouseTypes;
	}

	// 意向组团
	@RequestMapping(value = "projectPremisesList")
	@ResponseBody
	public List<ProjectPremises> projectPremisesList(Long projectId) {
		ProjectPremisesDto projectPremisesDto = new ProjectPremisesDto();
		projectPremisesDto.setProjectId(projectId);
		ResponseList<ProjectPremises> dResponseList = projectPremisesServiceFacade.findByDto(projectPremisesDto);
		List<ProjectPremises> projectPremisesList = new ArrayList<ProjectPremises>();
		if (dResponseList != null) {
			projectPremisesList = dResponseList.getEntity();
		}
		return projectPremisesList;
	}

	// 意向房源
	@RequestMapping(value = "projectRoomList")
	@ResponseBody
	public List<ProjectRoom> projectRoomList(ProjectRoomDto projectRoomDto) {
		ResponseList<ProjectRoom> dResponseList = projectRoomServiceFacade.findByDto(projectRoomDto);
		List<ProjectRoom> projectRoomList = new ArrayList<ProjectRoom>();
		if (dResponseList != null) {
			projectRoomList = dResponseList.getEntity();
		}
		return projectRoomList;
	}

	@RequestMapping(value = "userByProjectIdForGroup")
	@ResponseBody
	public List<User> userByProjectIdForGroup(Long projectId, Long isList, String resourcesCode) {
		User us = ShiroUtil.getCurrentUser();
		ResponseList<User> uResponseList = userServiceFacade.userByProjectIdForGroup(projectId, resourcesCode, isList,
				us.getId());
		List<User> userList = new ArrayList<User>();
		if (uResponseList != null) {
			userList = uResponseList.getEntity();
			if (isList != null && isList == 1) {
				List<User> newUserList = new ArrayList<User>();
				User u = new User();
				u.setUserName("全部");
				u.setId(-1l);
				newUserList.add(u);
				if (userList != null && userList.size() > 0) {
					for (User user : userList) {
						newUserList.add(user);
					}
					return newUserList;
				}else{
					return newUserList;
				}
			}
		}
		return userList;
	}

	@RequestMapping(value = "returnGroupList")
	@ResponseBody
	public List<SalesGroup> returnGroupList(Long projectId, String resourcesCode) {
		if(projectId==null){
			return new ArrayList<SalesGroup>();
		}
		
		User user = ShiroUtil.getCurrentUser();

		SalesGroupDto dto = new SalesGroupDto();
		dto.setProjectId(projectId);
		dto.setStatus("0");
		dto.setMerchantId(user.getMerchantId());
		if (StringUtils.isNotBlank(resourcesCode)) {
			dto.setResourcesCode(resourcesCode);
			dto.setPermissionUserId(user.getId());
		}
		ResponseList<SalesGroup> uResponseList = salesGroupServiceFacade.findAssignedSalesGroupByDto(dto);
		List<SalesGroup> selesGroupList = new ArrayList<SalesGroup>();
		if (uResponseList != null) {
			selesGroupList = uResponseList.getEntity();
		}
		return selesGroupList;
	}

	@RequestMapping(value = "returnGroupUserList")
	@ResponseBody
	public List<User> returnGroupUserList(SalesGroupUserDto dto, String resourcesCode, Long projectId) {

		User user = ShiroUtil.getCurrentUser();

		dto.setStatus("0");
		dto.setMerchantId(user.getMerchantId());
		if (StringUtils.isNotBlank(resourcesCode)) {
			dto.setResourcesCode(resourcesCode);
			dto.setPermissionUserId(user.getId());
		}
		
		if(null != projectId){
			Project project = projectServiceFacade.findById(projectId).getEntity();
			if(null != project){
				dto.setAccessCode(project.getProjectCode());
			}
		}
		
		ResponseList<SalesGroupUser> uResponseList = salesGroupUserServiceFacade.findAssignedSalesGroupByDto(dto);
		List<User> userList = new ArrayList<User>();
		if (uResponseList != null) {
			for (SalesGroupUser salesGroupUser : uResponseList.getEntity()) {
				Response<User> userResponse = userServiceFacade.findById(salesGroupUser.getUserId());
				if (userResponse.getEntity() != null) {
					userList.add(userResponse.getEntity());
				}
			}
		}
		return userList;
	}

	@RequestMapping("/provList")
	@ResponseBody
	public List<Area> getProvList() {
		// 获取对象集合
		ResponseList<Area> aResponseList = areaServiceFacade.selectAllProvince();
		List<Area> areaList = new ArrayList<Area>();
		if (aResponseList != null) {
			areaList = aResponseList.getEntity();
		}
		return areaList;
	}

	@RequestMapping("/cityList")
	@ResponseBody
	public List<Area> getCityList(String id) {
		AreaDto areaDto = new AreaDto();
		List<Area> areaList = new ArrayList<Area>();
		if (id == null) {
			return areaList;
		}
		Response<Area> aResponse = new Response<Area>();
		// 区分直辖市还是省份
		if (StringUtils.isNotBlank(id)) {
			aResponse = areaServiceFacade.findById(Long.valueOf(id));
		}

		Area area = aResponse.getEntity();
		if (area != null && area.getParentId() >= 10000) {
			areaDto.setType("1");
		}
		if (StringUtils.isNotBlank(id))
			areaDto.setParentId(Long.valueOf(id));
		// 获取对象集合
		ResponseList<Area> aResponseList = areaServiceFacade.selectCityOrArea(areaDto);
		if (aResponseList != null) {
			areaList = aResponseList.getEntity();
		}
		return areaList;
	}

	@RequestMapping("/areaList")
	@ResponseBody
	public List<Area> getAreaList(String id) {
		AreaDto areaDto = new AreaDto();
		List<Area> areaList = new ArrayList<Area>();
		if (id == null) {
			return areaList;
		}
		if (StringUtils.isNotBlank(id))
			areaDto.setParentId(Long.valueOf(id));
		// 获取对象集合
		ResponseList<Area> aResponseList = areaServiceFacade.findByDto(areaDto);
		if (aResponseList != null) {
			areaList = aResponseList.getEntity();
		}
		return areaList;
	}

	@RequestMapping("/detail")
	@ResponseBody
	public Map<String, Object> detail(Long id) {
		Map<String, Object> map = new HashMap<String, Object>();
		return map;

	}

	// 查看
	@RequestMapping(value = "customerDetail", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes customerDetail(Long id) {
		AjaxRes ar = getAjaxRes();
		try {
			Response<Customer> response = customerServiceFacade.findById(id);
			if (response.isSuccess()) {
				Customer customer = response.getEntity();
				CustomerComponentDto ccd = new CustomerComponentDto();
				BeanUtils.copyProperties(customer, ccd);

				BaseCodeValueDto bcvDto = new BaseCodeValueDto();
				bcvDto.setMerchantId(customer.getMerchantId());
				ResponseList<BaseCodeValue> bcvResList = baseCodeValueServiceFacade.selectListFilterDelFlag(bcvDto);
				Map<Long, String> bcvMap = new HashMap<Long, String>();
				if (bcvResList.isSuccess()) {
					List<BaseCodeValue> bcvList = bcvResList.getEntity();
					for (BaseCodeValue bcv : bcvList) {
						bcvMap.put(bcv.getId(), bcv.getCodeName());
					}
				}

				ccd.setCustomerSexName(StringUtils.isNotBlank(ccd.getCustomerSex()) ? CustomerSexEnum.getByNo(
						ccd.getCustomerSex()).getDes() : "");
				if (StringUtils.isNotBlank(ccd.getCustomerOrigin())) {
					ccd.setCustomerOriginName(bcvMap.get(Long.parseLong(ccd.getCustomerOrigin())));
				}
				if (StringUtils.isNotBlank(ccd.getPeDocumentType())) {
					ccd.setPeDocumentTypeName(bcvMap.get(Long.parseLong(ccd.getPeDocumentType())));
				}
				UserDto userDto = new UserDto();
				userDto.setUserCode(customer.getUserCode());
				ResponseList<User> userSponse = userServiceFacade.findByDto(userDto);
				if(userSponse.getEntity()!=null){
					ccd.setUserId(userSponse.getEntity().get(0).getId());
				}
				ar.setSucceed(ccd);
			} else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	@RequestMapping(value = "getArrayList")
	public @ResponseBody
	List<String> getArrayList(String type) {
		return ArrayAssembly.convestArrayList(type);
	}

	// 查看
	@RequestMapping(value = "customerPhone", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes customerPhone(String phone, Long projectId, Long id) {
		AjaxRes ar = getAjaxRes();
		try {
			User user = ShiroUtil.getCurrentUser();
			CustomerDto dto = new CustomerDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setCustomerPhone(phone);
			dto.setProjectId(projectId);
			dto.setId(id);
			ResponseList<Customer> response = customerServiceFacade.selectCustomerPhoneByListPC(dto);

			if (response.isSuccess()) {
				if (response.getEntity() != null && response.getEntity().size() > 0) {
					ar.setRes(Const.SUCCEED);
				} else {
					ar.setRes(Const.FAIL);
				}
			} else {
				ar.setRes(10000);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setRes(10000);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "findCustomerByNameOrPhone")
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_0, modelName = ModelTypeEnum.MODELTYPE_0, projectKey = "projectId")
	public Page<CustomerComponentDto> findCustomerByNameOrPhone(CustomerComponentDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		try {
			//当列表为未完善客户信息时只显示A级客户
			if(dto.getFillInfoDay() == 1){
				dto.setIntentionLevel("2");
			}
			// 数据权限
			User user = ShiroUtil.getCurrentUser();
			dto.setPermissionUserId(user.getId());
			dto.setMerchantId(user.getMerchantId());
			dto.setOrders(" t.create_time desc ");
			//当项目选择为全部时，只查询用户所有可以查看的项目
			if(dto.getProjectId() == null) {
				dto.setProjectIds(projectIds(user.getId(), user.getMerchantId()));
			}
			boolean needPermission = true;
			Page<CustomerComponentDto> response = customerServiceFacade.findCustomerPageByNameOrPhone(dto,
					PageUtil.begin(page, limit), limit, needPermission);
			if (response.getSuccess()) {
				if (null == response.getRows()) {
					// 手机号查询，先根据权限查询是否存在客户
					// 1、不存在，去除权限再次查询。
					// 2、存在，不做处理
					if (StringUtils.isNotEmpty(dto.getCustomerPhone())) {
						needPermission = false;
						response = customerServiceFacade.findCustomerPageByNameOrPhone(dto,
								PageUtil.begin(page, limit), limit, needPermission);
						if (response.getSuccess()) {
							if (null == response.getRows()) {
								response.setRows(new ArrayList<CustomerComponentDto>());
							} else {
								List<CustomerComponentDto> cusList = new ArrayList<CustomerComponentDto>();
								cusList = response.getRows();
								if (null != cusList && cusList.size() > 0) {
									for(CustomerComponentDto customerComponentDto: cusList) {
										customerComponentDto.setOutPermissionData(true);
									}
								}
								response.setRows(cusList);
							}
						}

					}
				}
				response.setPageNumber(page);
			}
			response.setError(response.getErrorMsg());
			return response;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<CustomerComponentDto>();
	}
	
	/**
	 * 导出客户信息
	 * @param response
	 * @param value
	 * @param ids
	 */
	@RequestMapping("expExcel")
	public void expExcel(HttpServletResponse response, String value, String ids, String condition){
		AjaxRes ar=getAjaxRes();
		/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:customer:export"))){
			CustomerComponentDto entity = new CustomerComponentDto();
			//当有勾选的数据时，只导出勾选数据，否则跟剧条件查询
			if(StringUtils.isNotBlank(ids)){
				entity.setIds(ids);
			}else{
				entity = queryCriteria(value, condition);
			}
			User user = ShiroUtil.getCurrentUser(); 
			entity.setPermissionUserId(user.getId());
			entity.setMerchantId(user.getMerchantId());
			entity.setOrders(" t.create_time desc ");
			ResponseList<CustomerComponentDto> resList = customerServiceFacade.selectCustomerAll(entity);
			if(resList.isSuccess()){
				List<CustomerComponentDto> dtoList = resList.getEntity();
				
				//excel导出
				String[] name = new String[]{"客户信息"}; //sheet信息
				List<String[]> headerList = new ArrayList<String[]>(); //表头集合
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
				//设置表头字段
				/*
				 * 需求变更,减少字段...保留备用
				 * String[] header = new String[]{"项目名称","经纪人","创建人","客户姓名","客户等级","是否多套交易","性别",
						"客户状态","联系电话","客户性质","获知途径","置业动机","关注重点","需求面积","需求楼层","生活服务",
						"生活配套","预算总价","预算单价","希望庭院具备功能","庭院需求面积","付款方式","家庭结构","意向物业类型",
						"需求户型规格","购买车位","接触方式","接触时间","沟通内容","证件类型","证件号码","出生日期","年龄",
						"固定电话","手机号码","邮箱","微信","车驾品牌","乐于参加的活动类型","邮编","学历","从事行业","公司性质",
						"公司年营业额","是否员工","户籍所在地","联系地址","居住地","小区","居住地详细地址","工作区","工作区详细地址","家庭年收入",
						"兴趣爱好","是否有子女","是否与老人同住","QQ号码","是否本公司业主","日常信息获取途径","本地购买房数",
						"目前家庭持有住宅数","目前居住的面积","目前居住/办公的房子属性","目前家庭住宅已按揭数","目前居住的物业类型",
						"目前居住的户型结构","工作日联系时间","工作日联系方式","周末联系时间","周末联系方式","备注"};
				*		
				*/
				String[] header = new String[]{"项目名称","经纪人","创建人","客户姓名","客户等级","性别",
						"客户状态","联系电话","客户性质","获知途径","置业动机","关注重点","需求面积","生活服务",
						"付款方式","来电接触时间","来电沟通内容","从事行业","居住地","工作区",
						"最后跟进时间","最后跟进内容","跟进次数","意向等级","是否多套交易"};
				if(MerchantEnum.GREEN_TOWN.getNo().equals(user.getMerchantId())){
					header = new String[]{"项目名称","经纪人","创建人","客户姓名","客户等级","性别",
							"客户状态","联系电话","客户性质","获知途径","置业动机","关注重点","需求面积","生活服务",
							"付款方式","来电接触时间","来电沟通内容","来访/电转访接触时间","来访/电转访沟通内容","从事行业","居住地","工作区",
							"最后跟进时间","最后跟进内容","跟进次数","意向等级","是否多套交易"};
				}
				headerList.add(header);
				
				//组装需要导出的excel数据
				//List<Map<String, String>> mapList = returnField(header, dtoList, entity.getProjectId());
				List<Map<String, String>> mapList = returnSimpleField(header, dtoList, entity.getProjectId());
				if(MerchantEnum.GREEN_TOWN.getNo().equals(user.getMerchantId())){
					mapList = returnSimpleFieldForLC(header, dtoList, entity.getProjectId());
				}
				list.add(mapList);
				//导出excel
				ExcelUtil.exportExcel(list, headerList, name, response);
			}
        }
	}
	
	/**
	 * 拼接查询条件
	 * @param value
	 * @return
	 */
	private CustomerComponentDto queryCriteria(String value, String condition){
		CustomerComponentDto entity = new CustomerComponentDto();
		if(StringUtils.isNotBlank(value)){
			JSONObject obj = JSONObject.fromObject(value);
			//项目名称
			if(StringUtils.isNotBlank(obj.getString("cbstore-inputEl")) 
					&& !"-1".equals(obj.getString("cbstore-inputEl"))){
				entity.setProjectId(Long.parseLong(obj.getString("cbstore-inputEl")));
			}
			//客户来源
			try {
				//普通版本的条件,绿城没有.会有异常
				if(StringUtils.isNotBlank(obj.getString("customerOrigin"))){
					entity.setCustomerOrigin(obj.getString("customerOrigin"));
				}
			}catch (Exception ex){

			}
			//客户状态
			if(StringUtils.isNotBlank(obj.getString("customerStatus"))){
				entity.setCustomerStatus(obj.getString("customerStatus"));
			}
			//首次接触方式
			if(StringUtils.isNotBlank(obj.getString("ftContactWay"))){
				entity.setFtContactWay(obj.getString("ftContactWay"));
			}
			//获知途径
			if(StringUtils.isNotBlank(obj.getString("informedWay"))){
				entity.setInformedWay(obj.getString("informedWay"));
			}
			//意向等级
			if(StringUtils.isNotBlank(obj.getString("intentionLevel"))){
				entity.setIntentionLevel(obj.getString("intentionLevel"));
			}
			//年龄查询区间开始时间
			if(StringUtils.isNotBlank(obj.getString("peAgeStart"))){
				entity.setPeAgeStart(obj.getString("peAgeStart"));
			}
			//未跟进情况区间结束天数
			if(StringUtils.isNotBlank(obj.getString("peAgeEnd"))){
				entity.setPeAgeEnd(obj.getString("peAgeEnd"));
			}
			//居住区- 省ID
			if(StringUtils.isNotBlank(obj.getString("peResidenceProvinceId"))){
				entity.setPeResidenceProvinceId(Long.parseLong(obj.getString("peResidenceProvinceId")));
			}
			//居住区- 市ID
			if(StringUtils.isNotBlank(obj.getString("peResidenceCityId"))){
				entity.setPeResidenceCityId(Long.parseLong(obj.getString("peResidenceCityId")));
			}
			//居住区- 区ID
			if(StringUtils.isNotBlank(obj.getString("peResidenceAreaId"))){
				entity.setPeResidenceAreaId(Long.parseLong(obj.getString("peResidenceAreaId")));
			}
			//置业动机
			if(StringUtils.isNotBlank(obj.getString("rqTheirMotives"))){
				entity.setRqTheirMotives(obj.getString("rqTheirMotives"));
			}
			//经纪人
			if(StringUtils.isNotBlank(obj.getString("userCode"))
					&& !"-1".equals(obj.getString("userCode"))){
				entity.setUserCode(obj.getString("userCode"));
			}
			//录入开始时间
			if(StringUtils.isNotBlank(obj.getString("createTimeBefore"))){
				entity.setCreateTimeBefore(obj.getString("createTimeBefore"));
			}
			//录入结束时间
			if(StringUtils.isNotBlank(obj.getString("createTimeAfter"))){
				entity.setCreateTimeAfter(obj.getString("createTimeAfter"));
			}
			//首次接触开始日期
			if(StringUtils.isNotBlank(obj.getString("ftContactTimeBefore"))){
				entity.setFtContactTimeBefore(obj.getString("ftContactTimeBefore"));
			}
			//首次接触结束日期
			if(StringUtils.isNotBlank(obj.getString("ftContactTimeAfter"))){
				entity.setFtContactTimeAfter(obj.getString("ftContactTimeAfter"));
			}
			//最后跟进开始日期
			if(StringUtils.isNotBlank(obj.getString("lastFollowTimeBefore"))){
				entity.setLastFollowTimeBefore(obj.getString("lastFollowTimeBefore"));
			}
			//最后跟进结束日期
			if(StringUtils.isNotBlank(obj.getString("lastFollowTimeAfter"))){
				entity.setLastFollowTimeAfter(obj.getString("lastFollowTimeAfter"));
			}
			//未跟进情况区间开始天数
			if(obj.get("lastFollowTimeStart") != null){
				entity.setLastFollowTimeStart(obj.getString("lastFollowTimeStart"));
			}
			//未跟进情况区间结束天数
			if(obj.get("lastFollowTimeEnd") != null){
				entity.setLastFollowTimeEnd(obj.getString("lastFollowTimeEnd"));
			}
			//未跟进情况redio
			if(obj.get("lastFollowTimeRadio") != null ){
				entity.setLastFollowTimeRadio(obj.getString("lastFollowTimeRadio"));
			}
		}
		//拼接客户查询条件
		if(StringUtils.isNotBlank(condition)){
			try {
				String sql = "";
				try {
					sql = URLDecoder.decode(condition, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				String appendSql = " and (t.customer_name LIKE '%" + sql + "%' or t.customer_phone = '" + sql
						+ "' or t.pe_mobile = '" + sql + "')";
				entity.setAppendSql(appendSql);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return entity;
	}
	
	/**
	 * 组装导出excel需要的
	 * @param header
	 * @param dtoList
	 * @return
	 */
	public List<Map<String, String>> returnField(String[] header, List<CustomerComponentDto> dtoList,
			Long projectId) {
		SimpleDateFormat sft_date = new SimpleDateFormat("yyyy-MM-dd");
		
		User user = ShiroUtil.getCurrentUser(); 
		//获取用户信息
		Map<Long, String> userMap = getUserName(user.getMerchantId());
		//获取业务参数
		Map<String, String> baseCodeValueMap = getBaseCodeValue(user.getMerchantId(), projectId); //获取业务参数
		//获取省市区信息
		Map<Long, String> areaMap = getArea(); 
		//正文数据组装
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		for(int i = 0; i < dtoList.size(); i++){
			CustomerComponentDto dto = (CustomerComponentDto)dtoList.get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put(header[0]+"_"+i, dto.getProjectName()); //项目名称
			map.put(header[1]+"_"+i, dto.getUserName()); //经纪人
			map.put(header[2]+"_"+i, dto.getCreateUserId() == null ? "" :
					userMap.get(dto.getCreateUserId())); //创建人
			map.put(header[3]+"_"+i, dto.getCustomerName()); //客户名称
			map.put(header[4]+"_"+i, StringUtils.isBlank(dto.getIntentionLevel()) ? "" : 
					IntentionLevelEnum.getByNo(dto.getIntentionLevel()).getDes()); //客户等级
			map.put(header[5]+"_"+i, "4".equals(dto.getCustomerTradeStatus()) ? "是":"否"); //是否多套交易
			map.put(header[6]+"_"+i, StringUtils.isBlank(dto.getCustomerSex()) ? "" : 
					CustomerSexEnum.getByNo(dto.getCustomerSex()).getDes()); //客户性别
			map.put(header[7]+"_"+i, StringUtils.isBlank(dto.getCustomerStatus()) ? "" : 
					CustomerStatusEnum.getByNo(dto.getCustomerStatus()).getDes()); //客户状态
			map.put(header[8]+"_"+i, dto.getCustomerPhone()); //联系电话
			map.put(header[9]+"_"+i, dto.getCustomerOrigin() == null ? "" : 
					baseCodeValueMap.get(dto.getCustomerOrigin())); //客户性质
			map.put(header[10]+"_"+i, dto.getInformedWay() == null ? "" :
					baseCodeValueMap.get(dto.getInformedWay())); //获知途径
			map.put(header[11]+"_"+i, dto.getRqTheirMotives() == null ? "" : 
					baseCodeValueMap.get(dto.getRqTheirMotives())); //置业动机
			map.put(header[12]+"_"+i, dto.getRqFocusId() == null ? "" :
					getValue(dto.getRqFocusId(), baseCodeValueMap)); //关注重点
			map.put(header[13]+"_"+i, StringUtils.isBlank(dto.getRqDemandArea()) ? "" :
					RqDemandAreaEnum.getByNo(dto.getRqDemandArea()).getDes()); //需求面积
			map.put(header[14]+"_"+i, dto.getRqDemandFloor() == null ? "" :
					baseCodeValueMap.get(dto.getRqDemandFloor())); //需求楼层
			map.put(header[15]+"_"+i, dto.getRqServicesId() == null ? "" :
					baseCodeValueMap.get(dto.getRqServicesId())); //生活服务
			map.put(header[16]+"_"+i, dto.getRqLifeSupport() == null ? "" :
					baseCodeValueMap.get(dto.getRqLifeSupport())); //生活配套
			map.put(header[17]+"_"+i, StringUtils.isBlank(dto.getRqBudgetSumprice()) ? "" :
					RqBudgetSumPriceEnum.getByNo(dto.getRqBudgetSumprice()).getDes()); //预算总价
			map.put(header[18]+"_"+i, StringUtils.isBlank(dto.getRqBudgetPrice()) ? "" :
					RqBudgetPriceEnum.getByNo(dto.getRqBudgetPrice()).getDes()); //预算单价
			map.put(header[19]+"_"+i, dto.getRqCourtyardFunction() == null ? "" :
					baseCodeValueMap.get(dto.getRqCourtyardFunction())); //希望庭院具备功能
			map.put(header[20]+"_"+i, dto.getRqCourtyardArea() == null ? "" : 
					dto.getRqCourtyardArea().toString()); //庭院需求面积
			map.put(header[21]+"_"+i, StringUtils.isBlank(dto.getRqPaymentMethod()) ? "" :
					PaymentMethodEnum.getByNo(dto.getRqPaymentMethod()).getDes()); //付款方式
			map.put(header[22]+"_"+i, dto.getFamilyJie() == null ? "" : 
					baseCodeValueMap.get(dto.getFamilyJie())); //家庭结构
			map.put(header[23]+"_"+i, StringUtils.isBlank(dto.getYixiangwuyeType()) ? "" :
					YiXiangWuYeEnum.getByNo(dto.getYixiangwuyeType()).getDes()); //意向物业类型
			map.put(header[24]+"_"+i, StringUtils.isBlank(dto.getXuqiuhuxingType()) ? "" :
					XuQiuHuXingEnum.getByNo(dto.getXuqiuhuxingType()).getDes()); //需求户型规格
			map.put(header[25]+"_"+i, StringUtils.isBlank(dto.getBuyCar()) ? "" :
					BuyCarEnum.getByNo(dto.getBuyCar()).getDes()); //购买车位
			map.put(header[26]+"_"+i, dto.getFtContactWay()); //接触方式
			map.put(header[27]+"_"+i, dto.getFtContactTime() == null ? "" :
					sft_date.format(dto.getFtContactTime())); //接触时间
			map.put(header[28]+"_"+i, dto.getFtContactContent()); //沟通内容
			map.put(header[29]+"_"+i, dto.getPeDocumentType() == null ? "" :
					baseCodeValueMap.get(dto.getPeDocumentType())); //证件类型
			map.put(header[30]+"_"+i, dto.getPeDocumentNumber()); //证件号码
			map.put(header[31]+"_"+i, dto.getPeBirth()); //出生日期
			map.put(header[32]+"_"+i, dto.getPeAge()); //年龄
			map.put(header[33]+"_"+i, dto.getPeTelephone()); //固定电话
			map.put(header[34]+"_"+i, dto.getPeMobile()); //手机号码
			map.put(header[35]+"_"+i, dto.getPeEmail()); //邮箱
			map.put(header[36]+"_"+i, dto.getPeWechat()); //微信
			map.put(header[37]+"_"+i, dto.getPeFrameBrandId() == null ? "" :
					baseCodeValueMap.get(dto.getPeFrameBrandId().toString())); //车驾品牌
			map.put(header[38]+"_"+i, dto.getPeActivityType() == null ? "" :
					baseCodeValueMap.get(dto.getPeActivityType())); //乐于参加的活动类型
			map.put(header[39]+"_"+i, dto.getPePostcode()); //邮编
			map.put(header[40]+"_"+i, dto.getPeAcademicQualifications() == null ? "" : 
					baseCodeValueMap.get(dto.getPeAcademicQualifications())); //学历
			map.put(header[41]+"_"+i, dto.getCongshihangye() == null ? "" : 
					baseCodeValueMap.get(dto.getCongshihangye())); //从事行业
			map.put(header[42]+"_"+i, dto.getCompanyXingzhi() == null ? "" : 
					baseCodeValueMap.get(dto.getCompanyXingzhi())); //公司性质
			map.put(header[43]+"_"+i, dto.getCompanyYingye()); //公司年营业额
			//是否员工
			if(StringUtils.isNotBlank(dto.getIsYuangong())){
				map.put(header[44]+"_"+i, "0".equals(dto.getIsYuangong()) ? "否" : "是" );
			}else{
				map.put(header[44]+"_"+i, ""); 
			}
			//户籍所在地
			String domicilePlace = "";
			if ("1".equals(dto.getPeDomicilePlace())) {
				domicilePlace = "本地";
			} else if ("2".equals(dto.getPeDomicilePlace())) {
				domicilePlace = "省外";
			} else if ("3".equals(dto.getPeDomicilePlace())) {
				domicilePlace = "省内";
			} else if ("4".equals(dto.getPeDomicilePlace())) {
				domicilePlace = "境外";
			}
			map.put(header[45]+"_"+i, domicilePlace);
			map.put(header[46]+"_"+i, dto.getPeContactAddress()); //联系地址
			//组装居住地
			StringBuffer placeOfAbode = new StringBuffer();
			//省
			if(dto.getPeResidenceProvinceId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceProvinceId()));
			}
			//市
			if(dto.getPeResidenceCityId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceCityId()));
			}
			//区
			if(dto.getPeResidenceAreaId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceAreaId()));
			}
			map.put(header[47]+"_"+i, placeOfAbode.toString()); //居住地
			map.put(header[48]+"_"+i, dto.getPePlot()); //小区
			map.put(header[49]+"_"+i, dto.getPeDetailedAddress()); //居住详细地址
			//组装工作区
			StringBuffer workingGround = new StringBuffer();
			//省
			if(dto.getPeWorkaroundProvinceId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundProvinceId()));
			}
			//市
			if(dto.getPeWorkaroundCityId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundCityId()));
			}
			//区
			if(dto.getPeWorkaroundAreaId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundAreaId()));
			}
			map.put(header[50]+"_"+i, workingGround.toString()); //工作区
			map.put(header[51]+"_"+i, dto.getPeWorkaroundAddress()); //工作详细地址
			map.put(header[52]+"_"+i, StringUtils.isBlank(dto.getPeHouseholdIncome()) ? "" : 
					PeHouseholdIncomeEnum.getByNo(dto.getPeHouseholdIncome()).getDes()); //家庭年收入
			map.put(header[53]+"_"+i, dto.getPeHobbyId() == null ? "" :
					baseCodeValueMap.get(dto.getPeHobbyId())); //兴趣爱好
			//是否有子女
			if(StringUtils.isNotBlank(dto.getIsZinv())){
				map.put(header[54]+"_"+i, "0".equals(dto.getIsZinv()) ? "否" : "是"); 
			}else{
				map.put(header[54]+"_"+i, ""); 
			}
			//是否与老人同住
			if(StringUtils.isNotBlank(dto.getIsLaoren())){
				map.put(header[55]+"_"+i, "0".equals(dto.getIsLaoren()) ? "否" : "是"); 
			}else{
				map.put(header[55]+"_"+i, ""); 
			}
			map.put(header[56]+"_"+i, dto.getQqNumber()); //QQ号码
			//是否本公司业主
			if(StringUtils.isNotBlank(dto.getIsYezhu())){
				map.put(header[57]+"_"+i, "0".equals(dto.getIsYezhu()) ? "否" : "是"); 
			}else{
				map.put(header[57]+"_"+i, ""); 
			}
			map.put(header[58]+"_"+i, dto.getRichangxinxi() == null ? "" : 
					baseCodeValueMap.get(dto.getRichangxinxi())); //日常信息获取途径
			map.put(header[59]+"_"+i, dto.getReLocalPurchase() == null ? "" : 
					dto.getReLocalPurchase().toString()); //本地购买房数
			map.put(header[60]+"_"+i, dto.getReCurrentHoldings() == null ? "" : 
					dto.getReCurrentHoldings().toString()); //目前家庭持有住宅数
			map.put(header[61]+"_"+i, StringUtils.isBlank(dto.getReCurrentlyArea()) ? "" : 
					ReCurrentlyAreaEnum.getByNo(dto.getReCurrentlyArea()).getDes()); //目前居住的面积
			map.put(header[62]+"_"+i, dto.getReCurrentlyHouse() == null ? "" : 
					baseCodeValueMap.get(dto.getReCurrentlyHouse())); //目前居住/办公的房子属性
			map.put(header[63]+"_"+i, dto.getReResidentialMortgage() == null ? "" : 
					dto.getReResidentialMortgage().toString()); //目前家庭住宅已按揭数
			map.put(header[64]+"_"+i, dto.getReCurrentlyProperty() == null ? "" : 
					baseCodeValueMap.get(dto.getReCurrentlyProperty())); //目前居住的物业类型
			map.put(header[65]+"_"+i, dto.getReCurrentlyStructure() == null ? "" :
					baseCodeValueMap.get(dto.getReCurrentlyStructure())); //目前居住的户型结构
			map.put(header[66]+"_"+i, StringUtils.isBlank(dto.getCoContactTime()) ? "" : 
					CoContactTimeEnum.getByNo(dto.getCoContactTime()).getDes()); //工作日联系时间
			map.put(header[67]+"_"+i, dto.getCoInformationDays() == null ? "" : 
					baseCodeValueMap.get(dto.getCoInformationDays())); //工作日联系方式
			map.put(header[68]+"_"+i, StringUtils.isBlank(dto.getCoContactWeekend()) ? "" :
					CoContactWeekendEnum.getByNo(dto.getCoContactWeekend()).getDes()); //周末联系时间
			map.put(header[69]+"_"+i, dto.getCoWeekendInformation() == null ? "" : 
					baseCodeValueMap.get(dto.getCoWeekendInformation())); //周末联系方式
			map.put(header[70]+"_"+i, dto.getRemark()); //备注
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 组装导出简易excel需要的
	 * @param header
	 * @param dtoList
	 * @return
	 */
	private List<Map<String, String>> returnSimpleField(String[] header, List<CustomerComponentDto> dtoList, Long projectId) {
		SimpleDateFormat sft_date = new SimpleDateFormat("yyyy-MM-dd");
		
		User user = ShiroUtil.getCurrentUser(); 
		//正文数据组装
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		if(dtoList == null) {
			return mapList;
		}
		//获取用户信息
		Map<Long, String> userMap = getUserName(user.getMerchantId());
		//获取业务参数
		Map<String, String> baseCodeValueMap = getBaseCodeValue(user.getMerchantId(), projectId); //获取业务参数
		//获取省市区信息
		Map<Long, String> areaMap = getArea(); 
		for(int i = 0; i < dtoList.size(); i++){
			CustomerComponentDto dto = (CustomerComponentDto)dtoList.get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put(header[0]+"_"+i, dto.getProjectName()); //项目名称
			map.put(header[1]+"_"+i, dto.getUserName()); //经纪人
			map.put(header[2]+"_"+i, dto.getCreateUserId() == null ? "" :
					userMap.get(dto.getCreateUserId())); //创建人
			map.put(header[3]+"_"+i, dto.getCustomerName()); //客户名称
			map.put(header[4]+"_"+i, StringUtils.isBlank(dto.getIntentionLevel()) ? "" : 
					IntentionLevelEnum.getByNo(dto.getIntentionLevel()).getDes()); //客户等级
			map.put(header[5]+"_"+i, StringUtils.isBlank(dto.getCustomerSex()) ? "" : 
					CustomerSexEnum.getByNo(dto.getCustomerSex()).getDes()); //客户性别
			map.put(header[6]+"_"+i, StringUtils.isBlank(dto.getCustomerStatus()) ? "" : 
					CustomerStatusEnum.getByNo(dto.getCustomerStatus()).getDes()); //客户状态
			map.put(header[7]+"_"+i, dto.getCustomerPhone()); //联系电话
			map.put(header[8]+"_"+i, dto.getCustomerOrigin() == null ? "" : 
					baseCodeValueMap.get(dto.getCustomerOrigin())); //客户性质
			map.put(header[9]+"_"+i, dto.getInformedWay() == null ? "" :
					baseCodeValueMap.get(dto.getInformedWay())); //获知途径
			map.put(header[10]+"_"+i, dto.getRqTheirMotives() == null ? "" : 
					baseCodeValueMap.get(dto.getRqTheirMotives())); //置业动机
			map.put(header[11]+"_"+i, dto.getRqFocusId() == null ? "" :
					getValue(dto.getRqFocusId(), baseCodeValueMap)); //关注重点
			map.put(header[12]+"_"+i, StringUtils.isBlank(dto.getRqDemandArea()) ? "" :
					RqDemandAreaEnum.getByNo(dto.getRqDemandArea()).getDes()); //需求面积
			map.put(header[13]+"_"+i, dto.getRqServicesId() == null ? "" :
				getValue(dto.getRqServicesId(), baseCodeValueMap)); //生活服务
			map.put(header[14]+"_"+i, StringUtils.isBlank(dto.getRqPaymentMethod()) ? "" :
					PaymentMethodEnum.getByNo(dto.getRqPaymentMethod()).getDes()); //付款方式
			//map.put(header[15]+"_"+i, dto.getFtContactWay()); //接触方式
			map.put(header[15]+"_"+i, dto.getFtContactTime() == null ? "" :
					sft_date.format(dto.getFtContactTime())); //来电接触时间
			map.put(header[16]+"_"+i, dto.getFtContactContent()); //来电沟通内容
			map.put(header[17]+"_"+i, dto.getCongshihangye() == null ? "" :
					baseCodeValueMap.get(dto.getCongshihangye())); //从事行业
			//组装居住地
			StringBuffer placeOfAbode = new StringBuffer();
			//省
			if(dto.getPeResidenceProvinceId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceProvinceId()));
			}
			//市
			if(dto.getPeResidenceCityId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceCityId()));
			}
			//区
			if(dto.getPeResidenceAreaId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceAreaId()));
			}
			map.put(header[18]+"_"+i, placeOfAbode.toString()); //居住地
			//组装工作区
			StringBuffer workingGround = new StringBuffer();
			//省
			if(dto.getPeWorkaroundProvinceId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundProvinceId()));
			}
			//市
			if(dto.getPeWorkaroundCityId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundCityId()));
			}
			//区
			if(dto.getPeWorkaroundAreaId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundAreaId()));
			}
			map.put(header[19]+"_"+i, workingGround.toString()); //工作区
			map.put(header[20]+"_"+i, dto.getLastFollowTime()==null ? "" :
				sft_date.format(dto.getLastFollowTime())); //最后跟进时间
			map.put(header[21]+"_"+i, dto.getFollowContent()); //跟进内容
			map.put(header[22]+"_"+i, dto.getFollowMonth()); //跟进次数
			map.put(header[23]+"_"+i, dto.getIntentionLevel() == null ? "" :
				IntentionLevelEnum.getByNo(dto.getIntentionLevel()).getDes()); //意向等级
			//是否多套交易
			String customerTradeStatus = "";
			if("4".equals(dto.getCustomerTradeStatus())) {
				customerTradeStatus = "是";
			} else {
				customerTradeStatus = "否";
			}
			map.put(header[24]+"_"+i, customerTradeStatus);
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 组装导出简易excel需要的
	 * @param header
	 * @param dtoList
	 * @return
	 */
	private List<Map<String, String>> returnSimpleFieldForLC(String[] header, List<CustomerComponentDto> dtoList, Long projectId) {
		SimpleDateFormat sft_date = new SimpleDateFormat("yyyy-MM-dd");

		User user = ShiroUtil.getCurrentUser();
		//正文数据组装
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		if(dtoList == null) {
			return mapList;
		}
		//获取用户信息
		Map<Long, String> userMap = getUserName(user.getMerchantId());
		//获取业务参数
		Map<String, String> baseCodeValueMap = getBaseCodeValue(user.getMerchantId(), projectId); //获取业务参数
		//获取省市区信息
		Map<Long, String> areaMap = getArea();
		for(int i = 0; i < dtoList.size(); i++){
			CustomerComponentDto dto = (CustomerComponentDto)dtoList.get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put(header[0]+"_"+i, dto.getProjectName()); //项目名称
			map.put(header[1]+"_"+i, dto.getUserName()); //经纪人
			map.put(header[2]+"_"+i, dto.getCreateUserId() == null ? "" :
					userMap.get(dto.getCreateUserId())); //创建人
			map.put(header[3]+"_"+i, dto.getCustomerName()); //客户名称
			map.put(header[4]+"_"+i, StringUtils.isBlank(dto.getIntentionLevel()) ? "" :
					IntentionLevelEnum.getByNo(dto.getIntentionLevel()).getDes()); //客户等级
			map.put(header[5]+"_"+i, StringUtils.isBlank(dto.getCustomerSex()) ? "" :
					CustomerSexEnum.getByNo(dto.getCustomerSex()).getDes()); //客户性别
			map.put(header[6]+"_"+i, StringUtils.isBlank(dto.getCustomerStatus()) ? "" :
					CustomerStatusEnum.getByNo(dto.getCustomerStatus()).getDes()); //客户状态
			map.put(header[7]+"_"+i, dto.getCustomerPhone()); //联系电话
			map.put(header[8]+"_"+i, dto.getCustomerOrigin() == null ? "" :
					baseCodeValueMap.get(dto.getCustomerOrigin())); //客户性质
			map.put(header[9]+"_"+i, dto.getInformedWay() == null ? "" :
					baseCodeValueMap.get(dto.getInformedWay())); //获知途径
			map.put(header[10]+"_"+i, dto.getRqTheirMotives() == null ? "" :
					baseCodeValueMap.get(dto.getRqTheirMotives())); //置业动机
			map.put(header[11]+"_"+i, dto.getRqFocusId() == null ? "" :
					getValue(dto.getRqFocusId(), baseCodeValueMap)); //关注重点
			map.put(header[12]+"_"+i, StringUtils.isBlank(dto.getRqDemandArea()) ? "" :
					RqDemandAreaEnum.getByNo(dto.getRqDemandArea()).getDes()); //需求面积
			map.put(header[13]+"_"+i, dto.getRqServicesId() == null ? "" :
					getValue(dto.getRqServicesId(), baseCodeValueMap)); //生活服务
			map.put(header[14]+"_"+i, StringUtils.isBlank(dto.getRqPaymentMethod()) ? "" :
					PaymentMethodEnum.getByNo(dto.getRqPaymentMethod()).getDes()); //付款方式
			//map.put(header[15]+"_"+i, dto.getFtContactWay()); //接触方式
			map.put(header[15]+"_"+i, dto.getFtContactTime() == null ? "" :
					sft_date.format(dto.getFtContactTime())); //来电接触时间
			map.put(header[16]+"_"+i, dto.getFtContactContent()); //来电沟通内容
			map.put(header[17]+"_"+i, dto.getFtContactTime1() == null ? "" :
					sft_date.format(dto.getFtContactTime1())); //来访/电转访接触时间
			map.put(header[18]+"_"+i, dto.getFtContactContent1()); //来访/电转访沟通内容
			map.put(header[19]+"_"+i, dto.getCongshihangye() == null ? "" :
					baseCodeValueMap.get(dto.getCongshihangye())); //从事行业
			//组装居住地
			StringBuffer placeOfAbode = new StringBuffer();
			//省
			if(dto.getPeResidenceProvinceId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceProvinceId()));
			}
			//市
			if(dto.getPeResidenceCityId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceCityId()));
			}
			//区
			if(dto.getPeResidenceAreaId() != null){
				placeOfAbode.append(areaMap.get(dto.getPeResidenceAreaId()));
			}
			map.put(header[20]+"_"+i, placeOfAbode.toString()); //居住地
			//组装工作区
			StringBuffer workingGround = new StringBuffer();
			//省
			if(dto.getPeWorkaroundProvinceId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundProvinceId()));
			}
			//市
			if(dto.getPeWorkaroundCityId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundCityId()));
			}
			//区
			if(dto.getPeWorkaroundAreaId() != null){
				workingGround.append(areaMap.get(dto.getPeWorkaroundAreaId()));
			}
			map.put(header[21]+"_"+i, workingGround.toString()); //工作区
			map.put(header[22]+"_"+i, dto.getLastFollowTime()==null ? "" :
					sft_date.format(dto.getLastFollowTime())); //最后跟进时间
			map.put(header[23]+"_"+i, dto.getFollowContent()); //跟进内容
			map.put(header[24]+"_"+i, dto.getFollowMonth()); //跟进次数
			map.put(header[25]+"_"+i, dto.getIntentionLevel() == null ? "" :
					IntentionLevelEnum.getByNo(dto.getIntentionLevel()).getDes()); //意向等级
			//是否多套交易
			String customerTradeStatus = "";
			if("4".equals(dto.getCustomerTradeStatus())) {
				customerTradeStatus = "是";
			} else {
				customerTradeStatus = "否";
			}
			map.put(header[26]+"_"+i, customerTradeStatus);
			mapList.add(map);
		}
		return mapList;
	}
	
	/**
	 * 获取用户信息
	 * @return
	 */
	private Map<Long, String> getUserName(Long merchantId){
		Map<Long, String> map = new HashMap<Long, String>();
		
		UserDto dto = new UserDto();
		dto.setMerchantId(merchantId);
		ResponseList<User> res = userServiceFacade.findByDto(dto);
		if(res.isSuccess()){
			for(User user : res.getEntity()){
				map.put(user.getId(), user.getUserName());
			}
		}
		return map;
	}
	
	/**
	 * 获取客户参数
	 * @param merchantId
	 * @return
	 */
	private Map<String, String> getBaseCodeValue(Long merchantId, Long projectId){
		Map<String, String> map = new HashMap<String, String>();
		BaseCodeValueDto dto = new BaseCodeValueDto();
		dto.setMerchantId(merchantId);
		dto.setProjectId(projectId);
		ResponseList<BaseCodeValue> res = baseCodeValueServiceFacade.findByDto(dto);
		if(res.isSuccess()){
			for(BaseCodeValue bcv : res.getEntity()){
				map.put(bcv.getId().toString(), bcv.getCodeName());
			}
		}
		return map;
	}
	/**
	 * 多ID字段获取value
	 * @param str
	 * @param bcvMap
	 * @return
	 */
	private String getValue(String str, Map<String, String> bcvMap) {
		String[] ids = str.split(",");
		StringBuffer name = new StringBuffer();
		for (int ii = 0; ii < ids.length; ii++) {
			String id = ids[ii];
			if (bcvMap.get(id) != null) {
				name.append(bcvMap.get(id));
			}
			if (ii != (ids.length - 1)) {
				name.append(",");
			}
		}
		return name.toString();
	}
	
	/**
	 * 获取地址信息
	 * @return
	 */
	private Map<Long, String> getArea(){
		Map<Long, String> map = new HashMap<Long, String>();
		
		AreaDto dto = new AreaDto();
		ResponseList<Area> res = areaServiceFacade.findByDto(dto);
		if(res.isSuccess()){
			for(Area ar : res.getEntity()){
				map.put(ar.getId(), ar.getAreaName());
			}
		}
		return map;
	}
	
	/**
	 * 跳转客户问卷
	 * @param customerId
	 * @param projectId
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value="toQuestionnaire")
	public String toQuestionnaire(Long customerId, Long projectId,ModelMap modelMap){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			modelMap.addAttribute("customerId", customerId);
			modelMap.addAttribute("projectId", projectId);
			//用于判断问卷类型
			Map<Long, String> map = new HashMap<Long, String>(16);
			//用于获取问卷名称
			Map<Long, String> mapName = new HashMap<Long, String>(16);
			//查询当前项目下的所有项目问卷
			ProjectQuestionnaireDto dto = new ProjectQuestionnaireDto();
			dto.setProjectId(projectId);
			dto.setIsValid(IsValidEnum.VALID.getNo());
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			ResponseList<ProjectQuestionnaire> response = projectQuestionnaireServiceFacade.findByDto(dto);
			List<ProjectQuestionnaire> listPQ = new ArrayList<ProjectQuestionnaire>();
			if(response.isSuccess() && response.getEntity() != null){
				listPQ = response.getEntity();
				for(ProjectQuestionnaire info : listPQ) {
					map.put(info.getId(), info.getType());
					mapName.put(info.getId(), info.getName());
				}
			}
			//查询是否有已经答过得问卷
			Long projectQuestionnaireId = null;
			CustomerProjectQuestionDto cpDto = new CustomerProjectQuestionDto();
			cpDto.setCustomerId(customerId);
			cpDto.setProjectId(projectId);
			cpDto.setIsValid(IsAvlidEnum.AVILD.getNo());
			cpDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			ResponseList<CustomerProjectQuestion> resCp = customerProjectQuestionServiceFacade.findByDto(cpDto);
			if(resCp.isSuccess() && resCp.getEntity() != null){
				projectQuestionnaireId = resCp.getEntity().get(0).getProjectQuestionnaireId();
			}
			//判断客户是否填写过问卷，当客户填写过时，判断问卷属于什么类型，是否可以展示问卷下拉列表
			if(projectQuestionnaireId == null) {
				modelMap.addAttribute("questionnaireList", listPQ);
			} else {
				if("2".equals(map.get(projectQuestionnaireId))) {
					modelMap.addAttribute("questionnaireList", listPQ);
				} else {
					//当问卷类型为题库选题时，不需要展示问卷下拉列表
					List<ProjectQuestionnaire> list = new ArrayList<ProjectQuestionnaire>();
					ProjectQuestionnaire pq = new ProjectQuestionnaire();
					pq.setId(projectQuestionnaireId);
					pq.setName(mapName.get(projectQuestionnaireId));
					list.add(pq);
					modelMap.addAttribute("questionnaireList", list);
				}
			}
			return "/customer/questionnaire/questionnaire";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 保存客户列表设置
	 * @param customerSort
	 * @param customerHideField
	 * @return
	 */
	@RequestMapping("userSettings")
	@ResponseBody
	public AjaxRes userSettings(String customerSort, String customerHideField) {
		AjaxRes ar = getAjaxRes();
		// 数据权限
		User user = ShiroUtil.getCurrentUser();
		if(user == null) {
			ar.setRes(0);
			return ar;
		}
		//保存设置
		UserDto dto = new UserDto();
		dto.setId(user.getId());
		dto.setCustomerSort(customerSort);
		dto.setCustomerHideField(customerHideField);
		Response<Integer> res = userServiceFacade.updateByPrimaryKey(dto, false, true);
		if(res.isSuccess()) {
			if(res.getEntity() > 0) {
				//保存成功
				ar.setRes(1);
				//将新设置保存到用户session
				user.setCustomerSort(customerSort);
				user.setCustomerHideField(customerHideField);
				SessionUtil.setSession(Const.SESSION_USER, user);
				return ar;
			}
		}
		ar.setRes(0);
		return ar;
	}
	
	/**
	 * 新增电转访
	 * @param customerId
	 * @param projectId
	 * @param ftContactContent
	 * @return
	 */
	@RequestMapping("addContactWay")
	@ResponseBody
	public AjaxRes addContactWay(Long customerId, Long projectId, 
			String ftContactContent) {
		AjaxRes ar = getAjaxRes();
		try {
			CustomerDto entity = new CustomerDto();
			entity.setFtContactContent1(ftContactContent);
			entity.setId(customerId);
			entity.setProjectId(projectId);
			AddContactWayResDto resDto = customerServiceFacade.addContactWay(entity);
			ar.setRes(Integer.parseInt(resDto.getResult()));
		} catch (Exception e) {
			logger.error("保存电转访失败", e);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		return ar;
	}
}
